iText PDF / A-2 Java在页脚中添加总页数

时间:2018-11-16 04:48:35

标签: itext pdfa headerfooter

我需要将总页数添加到使用Java中的iText创建的PDF / A-2文档中。正在使用以下代码:

public class HeaderFooterPageEvent extends PdfPageEventHelper {

 Font fontHEADER = null;

 /** The template with the total number of pages. */
 PdfTemplate total;

public HeaderFooterPageEvent() {
    try {
        fontHEADER = new Font(BaseFont.createFont("OpenSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8, Font.BOLD);
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
 }

 @Override
 public void onOpenDocument(PdfWriter writer, Document document) {
    total = writer.getDirectContent().createTemplate(30, 16);
    super.onOpenDocument(writer, document);
 } 

 @Override
 public void onCloseDocument(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    ColumnText.showTextAligned(total, Element.ALIGN_RIGHT,
            new Phrase(String.valueOf(writer.getPageNumber() - 1)),fontHEADER),
            document.right() - document.rightMargin()+5, 
            document.bottom() - 10, 0);
    super.onCloseDocument(writer, document);
 }
}

在创建PDF时,将调用以下代码:

    Document document = new Document(PageSize.A4, 15, 15, 30, 20);

    PdfAWriter writer = PdfAWriter.getInstance(document, new FileOutputStream(dest), PdfAConformanceLevel.PDF_A_2A);
    writer.createXmpMetadata();
    writer.setTagged();

 // add header and footer
    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    writer.setPageEvent(event);

    document.open();
    document.addLanguage("en-us");
    File file = new File("sRGB_CS_profile.icm");
    ICC_Profile icc = ICC_Profile
            .getInstance(new FileInputStream(file));
    writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
    Paragraph p=new Paragraph("Page 1 content",fontEmbedded); //setting an embedded font
    p.setSpacingBefore(30f);
    document.add(p);
    document.newPage();
    document.add(new Paragraph("Content of next page goes here",fontEmbedded));


    document.close();

现在,当我们在2个页面上添加内容并使用document.newPage()添加新页面时,将生成运行时异常The page 3 was requested but the document has only 2 pages.,该问题的解决方案是什么?

0 个答案:

没有答案