簡體   English   中英

itext生成的pdf無法在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM