我正在尝试下载一个运行时生成的PDF文件(使用iTextPDF生成的PDF文件)在Springboot服务,并希望通过angular 6.0在新选项卡中打开该文件。我试着遵循这个,如何下载一个在我的服务器(springboot)上生成的angular的pdf文件?但错误为“无法加载PDF文档”。代码出了什么问题?
this.service.PrintPDF(this.quotations).subscribe((data: Blob) => {
var file = new Blob([data], { type: 'application/pdf' })
var fileURL = URL.createObjectURL(file);
// if you want to open PDF in new tab
window.open(fileURL);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
// a.download = 'bill.pdf';
document.body.appendChild(a);
a.click();
},
(error) => {
console.log('getPDF error: ',error);
}
);
PrintPDF(quotations: Quotation[]) {
let url = this.PDF_URL;
var authorization = 'Bearer ' + sessionStorage.getItem("key");
const headers = new HttpHeaders({
'Content-Type': 'application/json',
responseType: 'blob',
"Authorization": authorization
});
return this.http.post<Blob>(url, quotations, {
headers: headers, responseType:'blob' as 'json'}).pipe(map(
(response) => {
return response;
},
(error) => {console.log(error.json());}
));
@PostMapping(value = "/generatepdf")
public void downloadFile(@RequestBody List<QuotationDTO> quotationDTOs, HttpServletRequest request, HttpServletResponse response) {
try {
quotationService.GeneratePDF(quotationDTOs, request, response);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Springboot服务:
public String GeneratePDF(java.util.List<QuotationDTO> quotationDTOs, HttpServletRequest request,
HttpServletResponse response) throws DocumentException, IOException {
response.setContentType("application/blob");
// Response header
response.setHeader("Pragma", "public");
response.setHeader("responseType", "blob");
response.setHeader("Content-Disposition", "attachment; filename=\"" + "Quotation" + "\"");
// OutputStream os = response.getOutputStream();
Document document = new Document(PageSize.A4, 50, 50, 5 , 5);
String current = sdf.format(new Timestamp(System.currentTimeMillis())).toString();
String reportName = "report"+current;
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(<Path>));
document.open();
// Write Content
document.close();
PdfWriter.getInstance(document, response.getOutputStream());
return reportName+".pdf";
}
我找到了解决我问题的办法。我想从内存里发送PDF。现在在一个位置上创建pdf,并从该位置发送、读取pdf。不确定iTextPDF是否支持内存pdf创建。
Springboot服务:
public Resource GeneratePDF(java.util.List<QuotationDTO> quotationDTOs, HttpServletRequest request)
throws DocumentException, IOException {
Document document = new Document(PageSize.A4, 50, 50, 5 , 5);
String current = sdf.format(new Timestamp(System.currentTimeMillis())).toString();
String reportName = "report"+current;
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("PATH"));
document.open();
//Write PDF
document.close();
try {
Path filePath = this.fileStorageLocation.resolve(reportName+".pdf").normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new MyFileNotFoundException("File not found " + reportName+".pdf");
}
} catch (MalformedURLException ex) {
throw new MyFileNotFoundException("File not found " + reportName+".pdf", ex);
}
}
Springboot控制器:
@PostMapping(value = "/generatepdf")
public ResponseEntity<Resource> downloadFile(@RequestBody List<QuotationDTO> quotationDTOs, HttpServletRequest request) {
try {
Resource resource = quotationService.GeneratePDF(quotationDTOs, request);
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
}
// Fallback to the default content type if type could not be determined
if(contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
角度服务:
PrintPDF(quotations: Quotation[]) {
let url = this.PDF_URL;
var authorization = 'Bearer ' + sessionStorage.getItem("key");
let headerOptions = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/pdf',
"Authorization": authorization
// 'Accept': 'application/octet-stream', // for excel file
});
let requestOptions = { headers: headerOptions, responseType: 'blob' as 'blob' };
this.http.post(url, quotations, requestOptions).pipe(map((data: any) => {
let blob = new Blob([data], {
type: 'application/pdf' // must match the Accept type
// type: 'application/octet-stream' // for excel
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
// link.download = 'samplePDFFile.pdf';
link.target = '_blank';
link.click();
window.URL.revokeObjectURL(link.href);
})).subscribe((result: any) => {
});
}
Angular组件只是调用Angular服务
“我想下载一个从基于spring的restful web服务发送的.pdf文件到我的angular应用程序。如何下载,我的angular应用程序或Spring Boot上是不是缺少了一些代码?” 我正在从angular 6应用程序向spring-boot服务器发送一个HTTP GET请求,该服务器生成一个.pdf文件,然后将这个.pdf文件作为blob发送给我,但当我试图在angular侧创建一个
Error:SyntaxError:在JSON中,在XMLHttpRequest.onload Oketask(http://localhost:4200/polyfills.js:2780:60)在zone.push../node_modules/zone.js/dist/zone.js.zone.runtask(http://localhost:4200/polyfills.js:2553:4
如何通过< code>ItextSharp合并多个pdf文件(运行时生成),然后打印它们。 我找到了下面的链接,但考虑到存储的pdf文件不是我的情况,该方法需要pdf名称。 我有多个报告,我将通过以下方法将它们转换为< code>pdf文件: 现在我想将所有生成的文件()合并到一个pdf文件中以打印它
无法生成pdf下载获取Android.os.fileuriexposedexception错误:file:///storage/emulated/0/download/inv-0002.pdf通过intent.getdata()超出应用程序公开
大家好,我是android开发的新手,我想在我的应用程序webView中下载一个pdf文件,我使用下面的代码,但是当我尝试打开它时,应用程序将我重定向到my phone web浏览器,我该如何解决它,我该如何在我的webView中下载pdf文件