【发布时间】:2020-12-11 05:45:26
【问题描述】:
我在这里看到了很多答案,我复制了一些示例并尝试应用它,但我不知道如何使这个工作。我正在尝试使用 PDFBox 创建一个文件并使用响应发送它,以便用户可以下载它。到目前为止,我可以下载该文件,但它是空白的。我已经尝试使用 PDFBox 从我的计算机加载一个示例文件并下载它,但它以相同的方式出现,空白。我现在使用的代码是:
@GET
@Path("/dataPDF")
@Produces("application/pdf")
public Response retrievePDF(){
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
output = createPDF();
ResponseBuilder response = Response.ok(output.toByteArray(), "application/pdf");
response.header("Content-Disposition","attachment; filename=file.pdf");
return response.build();
}
catch (Exception ex) {
ex.printStackTrace();
return Response.status(Response.Status.NOT_FOUND).build();
}
public ByteArrayOutputStream createPDF() throws IOException {
PDFont font = PDType1Font.HELVETICA;
PDPageContentStream contentStream;
ByteArrayOutputStream output =new ByteArrayOutputStream();
PDDocument document =new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(font, 20);
contentStream.newLineAtOffset(10, 770);
contentStream.showText("Amount: $1.00");
contentStream.endText();
contentStream.beginText();
contentStream.setFont(font, 20);
contentStream.newLineAtOffset(200, 880);
contentStream.showText("Sequence Number: 123456789");
contentStream.endText();
contentStream.close();
document.save(output);
document.close();
return output;
}
更新 1:所以正在创建文件,现在我只是无法将它发送到网络,我正在使用 ReactJS。我尝试调整我用来下载 csv 文件的结构,这里是:
const handleExportPDF= fileName => {
FileController.retrievePDF().then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
});
};
static retrievePDF() {
const { method, url } = endpoints.retrievePDF();
return api[method](url,{
responseType: "application/pdf"
});
}
export const fileEndpoints = {
retrievePDF: () => ({
method: "get",
url: `/export/dataPDF`
})
};
更新 2:如果有人在这里绊倒,我可以在这里用这个答案解决问题:PDF Blob - Pop up window not showing content。重点在改变
responseType: "application/pdf" 到 responseType: 'arraybuffer'
即使它已经可以改变这个,我也改变了
window.URL.createObjectURL(new Blob([response.data])); 到 window.URL.createObjectURL(new Blob([response.data]), {type: 'application/pdf'});
【问题讨论】:
标签: java reactjs rest pdf-generation pdfbox