![](/img/trans.png)
[英]How to read PDF file through iText and display it as in Adobe Reader?
[英]Itext generated pdf not opening in Adobe reader?
我正在使用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;
}
谁能帮忙吗? 谢谢
ps我已经创建了一个示例文件。
上面@mkl指出的原因就是问题。 我使用了错误的字体。 我从这里下载了字体,现在可以使用了。
嗨,您可以以此替换最后4行。 编码之前不需要关闭ByteArrayOutputStream。
byte[] bytes = baos.toByteArray();
String base64 = Base64.getEncoder().encodeToString(bytes);
return base64;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.