编辑现有PDF文档时出错:找不到PDF标题签名

时间:2013-07-25 18:55:30

标签: java pdf itext

我正在尝试将内容添加到现有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();
  }
 }

}

1 个答案:

答案 0 :(得分:0)

尝试替换你的行

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

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

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