java - 如何避免 com.lowagie.text.BadElementException

标签 java itext

关于this例如我创建了一个用于页眉页脚和页码的程序。 但是在运行该程序时,它会抛出 BadElementException:模板不能为空。

以下是我的完整代码

 import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import wt.query.QueryException;
import wt.util.WTException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;




public class TestHF2 {

    public static final String RESULT="Pagenumber.pdf";

    public class HeaderFooter extends PdfPageEventHelper
    {
        String header;
        PdfTemplate total;

        public void setHeader(String header)
        {
            this.header=header;
        }
        public void openDocument(PdfWriter writer,Document document)
        {
            total=writer.getDirectContent().createTemplate(30, 16);
        }
        public void onEndPage(PdfWriter writer,Document document)
        {
            PdfPTable table=new PdfPTable(3);
            try {
                table.setWidths(new int[]{24,24,2});
                table.setTotalWidth(527);
                table.setLockedWidth(true);
                table.getDefaultCell().setFixedHeight(20);
                table.getDefaultCell().setBorder(Rectangle.BOTTOM);
                table.addCell(header);
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(String.format("Page %d of", writer.getPageNumber()));
                PdfPCell cell=new PdfPCell(Image.getInstance(total));
                cell.setBorder(Rectangle.BOTTOM);
                table.addCell(cell);
                table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        public void onCloseDocument(PdfWriter writer,Document document)
        {
            ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber()-1)), 2, 2, 0);
        }
        @SuppressWarnings("unchecked")
        public void createPDF() throws QueryException, WTException, DocumentException, IOException
        {
            String PartNO="GT024";
            List L=winpar.start(PartNO);
            List M=child.start1(PartNO);
            Iterator it = L.iterator();
              Iterator its = M.iterator();
             Document document=new Document(PageSize.A4,36,36,54,36);
             PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(RESULT));
             HeaderFooter event=new HeaderFooter();
             writer.setPageEvent(event);
             document.open();
             @SuppressWarnings("unused")
            PdfContentByte contentByte=writer.getDirectContent();
             PdfPTable table=new PdfPTable(4);
             table.setWidthPercentage(100);
             table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
             table.getDefaultCell().setBorder(Rectangle.BOTTOM);
             table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
             table.getDefaultCell().setFixedHeight(20);
             LineSeparator ls=new LineSeparator();
             document.add(ls);

             table.addCell("Name");
             table.addCell("Number");
             table.addCell("State");
             table.addCell("Container");
             LineSeparator ls1=new LineSeparator();
             document.add(ls1);
             while (it.hasNext()) {
                    insertCell(table, it.next().toString(), Element.ALIGN_LEFT, 1);
                     insertCell(table, it.next().toString(), Element.ALIGN_LEFT, 1);
                     insertCell(table, it.next().toString(), Element.ALIGN_LEFT, 1);
                     insertCell(table, it.next().toString(), Element.ALIGN_LEFT, 1);
                 }
                 while (its.hasNext()) {
                     insertCell(table, its.next().toString() , Element.ALIGN_LEFT, 1);
                    insertCell(table, its.next().toString(), Element.ALIGN_LEFT, 1);
                    insertCell(table, its.next().toString(), Element.ALIGN_LEFT, 1);
                     insertCell(table, its.next().toString(), Element.ALIGN_LEFT, 1);
                 }
                 document.add(table);
                 document.close();
                 File file = new File("PageAndheader.pdf");
                 if (file.toString().endsWith(".pdf")) {
                     Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file);
                 } else {
                     Desktop desktop = Desktop.getDesktop();
                     desktop.open(file);
                 }

                }


        }
    private static void insertCell(PdfPTable table, String text, int align, int colspan) {

        //create a new cell with the specified Text and Font
        PdfPCell cell = new PdfPCell(new Phrase(text.trim()));
        cell.setBorder(Rectangle.NO_BORDER);
        //set the cell alignment
        cell.setHorizontalAlignment(align);
        //set the cell column span in case you want to merge two or more cells
        cell.setColspan(colspan);
        //in case there is no text and you wan to create an empty row
        if (text.trim().equalsIgnoreCase("")) {
            cell.setMinimumHeight(10f);
        }
        //add the call to the table
        table.addCell(cell);

    }


public static void main(String args[]) throws QueryException, DocumentException, WTException, IOException,ClassCastException, com.lowagie.text.DocumentException
{
    TestHF2 ot=new TestHF2();
    TestHF2.HeaderFooter obj=ot.new HeaderFooter();
    obj.createPDF();

}   


}

我得到这样的输出

    `Query size ===8
child size is: 4
com.itextpdf.text.BadElementException: The template can not be null.
    at com.itextpdf.text.ImgTemplate.<init>(ImgTemplate.java:74)
    at com.itextpdf.text.Image.getInstance(Image.java:589)
    at ext.gt.checkOut.TestHF2$HeaderFooter.onEndPage(TestHF2.java:61)
    at com.itextpdf.text.pdf.PdfDocument.newPage(PdfDocument.java:858)
    at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:793)
    at com.itextpdf.text.Document.close(Document.java:416)
    at ext.gt.checkOut.TestHF2$HeaderFooter.createPDF(TestHF2.java:118)
    at ext.gt.checkOut.TestHF2.main(TestHF2.java:154)
Exception in thread "main" java.lang.NullPointerException
    at com.itextpdf.text.pdf.ColumnText.showTextAligned(ColumnText.java:1189)
    at com.itextpdf.text.pdf.ColumnText.showTextAligned(ColumnText.java:1251)
    at ext.gt.checkOut.TestHF2$HeaderFooter.onCloseDocument(TestHF2.java:73)
    at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:799)
    at com.itextpdf.text.Document.close(Document.java:416)
    at ext.gt.checkOut.TestHF2$HeaderFooter.createPDF(TestHF2.java:118)
    at ext.gt.checkOut.TestHF2.main(TestHF2.java:154)

    `

从这个类中,我已将其他两个类称为我的自定义类。但我不知道为什么会收到 BadElementException:模板不能为空。此外,我还引用了 Page X of Y 问题的文档。所以我在这里创建了一个模板。但我不明白为什么它会出现。

抱歉添加了我的程序的整个部分。我别无选择。提前感谢您阅读我的所有问题。我需要一些帮助

最佳答案

执行 onEndPage() 时,“total”变量为 null。

关于java - 如何避免 com.lowagie.text.BadElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15022904/

相关文章:

java - 将 Gson 添加到 pom.xml 但未找到

java - jmock 和mockito 如何创建包装器?

java - 通过父类字段值对Jackson进行反序列化子类

c# - ItextSharp Font.BaseFont 为某些字体返回 Null

java - 如何从 PDF 文件中删除所有图像/绘图并仅保留 Java 中的文本?

Java 阻止用户输入除整数以外的任何内容

java - 将单行 HTML 文件分割为格式良好的 HTML 文件

java - iText5 PDF 内容在页脚上被覆盖

java - XML 属性名称中的符号 '#' 会产生 DOMException

pdf - 当我使用 itext 调用 BaseFont.createFont() 时,如何知道正确的编码?