0

我正在尝试将内容添加到现有的 PDF 文件中。但是代码给了我以下错误,

com.itextpdf.text.exceptions.InvalidPdfException:未找到 PDF 标头签名。

这是我的代码,我在这里做错了什么?

import java.awt.Color;
import java.io.FileOutputStream;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class PDF {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Document document = new Document();
  try {
   PdfWriter writer = PdfWriter.getInstance(document,
     new FileOutputStream("output.pdf"));

   document.open();

   PdfContentByte cb = writer.getDirectContent();

   // Load existing PDF
   PdfReader reader = new PdfReader(new PdfReader(
     "input.pdf"));
   PdfImportedPage page = writer.getImportedPage(reader, 1);

   // Copy first page of existing PDF into output PDF
   document.newPage();
   cb.addTemplate(page, 0, 0);

   // Add your new data / text here
   // for example...
   Font font = new Font();
   font.setColor(BaseColor.BLUE);
   font.setStyle(Font.UNDERLINE);
   Paragraph paragraph = new Paragraph();
   paragraph.setLeading(0, 25);
   paragraph.setAlignment(Paragraph.ALIGN_LEFT);
   paragraph.setAlignment(Paragraph.ALIGN_BASELINE);
   Chunk chunk = new Chunk("Java", font)
     .setAnchor("http://www.google.com");
   paragraph.add(chunk);
   document.add(paragraph);

   document.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
4

1 回答 1

0

尝试更换您的线路

PdfReader reader = new PdfReader(new PdfReader("input.pdf"));

PdfReader reader = new PdfReader("input.pdf");

这应该这样做。并且不要忘记之后关闭阅读器......

于 2013-07-26T12:59:37.327 回答