Adding page to existing PDF com.itextpdf.text.exce

2019-07-23 07:41发布

问题:

I am trying to add a page to an already created PDF using iText 1.02b using Java 1.5. When I add the new page to the existing PDF I get the exception that I included. Here is the code in the method we are having the issue.

public static File addSignaturePageToPDF(String fileName, InputStream fileInputStream, SignatureTemplateInfo signaturePageInfo, HttpServletRequest argRequest) throws Exception {

int splitIdx = fileName.lastIndexOf(".");
        File signedFile = File.createTempFile(fileName.substring(0,splitIdx), fileName.substring(splitIdx));
        SignatureModel signatureModel = SignatureHelper.getSignatureModel(signaturePageInfo.getCaseHeaders(), signaturePageInfo.getEventSubTp(), signaturePageInfo.getSignatureId(), argRequest);

        byte[] signaturePdfAsBytes = SignatureHelper.createSignature(signatureModel, argRequest);
        byte[] mainPdfAsBytes = getByteArrayFromInputStream(fileInputStream);
    PdfReader mainPdfReader = new PdfReader(mainPdfAsBytes);  << Exception here
    PdfReader signaturePdfReader = new PdfReader(signaturePdfAsBytes); 

Exception:

com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found.
    at com.itextpdf.text.pdf.PRTokeniser.checkPdfHeader(PRTokeniser.java:205)
    at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:496)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:189)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:178)
    at icis.common.util.ConvertDocument.addSignaturePageToPDF(ConvertDocument.java:96)
    at icis.cr.common.file.ViewFileAction.executeProcess(ViewFileAction.java:71)
    at icis.common.action.BaseICISAction.execute(BaseICISAction.java:134)
    at icis.cr.common.BaseCRAction.execute(BaseCRAction.java:41)

Thanks.

回答1:

The exception tells you that the first bytes obtained from your fileInputStream aren't equal to '%', 'P', 'D', 'F', '-', '1', '.'.

Maybe the file you're trying to inspect is empty, maybe the InputStream can't be read correctly,...

Many people before you have encountered and fixed the same problem:

  • How to solve pdf header signature not found error?
  • PDF header signature not found, iText
  • com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found
  • iTextSharp exception: PDF header signature not found
  • Error PDF header signature not found
  • itextsharp multipage pdf form
  • ...

You should debug your code, by saving mainPdfAsBytes to a file and by examining that file. Is it really a PDF file? iText tells you it doesn't start with %PDF-1..



标签: java pdf itext