【发布时间】:2019-06-25 08:25:37
【问题描述】:
我正在使用 itext(版本 5.5.4)在服务器中创建 pdf 文件。当我在客户端下载文件并尝试在 adobe reader 中打开它时,它没有打开,并弹出一条消息说“处理页面时出错。阅读此文档时出现问题(129)”。
这个 pdf 文件可以在其他应用程序(如 evince、foxit 和 google chrome)中打开。以下是我正在使用的部分代码。
public static String genPdfAsBase64(String orientation, JSONObject data)
throws IOException, DocumentException {
if(orientation.equals("landscape")) {
doc = new Document(PageSize.A4.rotate(), 10f, 10f, 50f, 5f);
} else {
doc = new Document();
}
JSONArray header = (JSONArray)data.get("header");
JSONArray body = (JSONArray)data.get("body");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(doc, baos);
TableHeader evt = new TableHeader();
evt.setOrientation(orientation);
writer.setPageEvent(evt);
doc.addAuthor(AUTHOR);
doc.open();
Image img = Image.getInstance(Base64.decode(BASE_64_IMG));
img.setAlignment(Image.ALIGN_MIDDLE);
img.setBorder(Rectangle.NO_BORDER);
img.scaleToFit(20f,20f);
doc.add(img);
Paragraph par = new Paragraph("Report", new Font(FontFamily.HELVETICA, 10));
par.setAlignment(Element.ALIGN_CENTER);
doc.add(par);
doc.add(new Paragraph(" "));
PdfPTable table = new PdfPTable(header.size());
table.setTotalWidth(1500);
table.setHeaderRows(1);
/*Header*/
for(Object obj : header) {
String text = (String)obj;
PdfPCell cell = new PdfPCell(new Phrase(text));
cell.setBackgroundColor(headerCol);
table.addCell(cell);
}
/*Body*/
for(int i=0; i<body.size(); i++) {
JSONArray row = (JSONArray)body.get(i);
for(Object obj : row) {
String text = String.valueOf(obj);
PdfPCell cell = new PdfPCell(new Phrase(text, sansFont));
if(i%2 != 0) {
cell.setBackgroundColor(evenCol);
}
table.addCell(cell);
}
}
doc.add(table);
doc.close();
byte[] bytes = baos.toByteArray();
baos.close();
String base64 = Base64.encodeBytes(bytes);
return base64;
}
有人可以帮忙吗? 谢谢
附言我创建了一个sample 文件。
【问题讨论】:
-
请分享有问题的 PDF。
-
谢谢,但我不能分享。将尝试创建一个虚拟 pdf。
-
@mkl 我添加了一个示例文件的链接。
-
看起来问题出在
sansFont上,至少通过将其从共享文件中删除,原始问题就消失了。看起来您的代码中根本没有定义该字体。所以请在genPdfAsBase64中定义该字体,并且不要在调用中重复使用它。 -
@mkl 我已经删除了字体。它没有帮助。你能告诉我你是如何从pdf中删除字体的吗?
标签: java server itext pdf-generation