2016-11-01 58 views
1

當運行此代碼時,PdfDocument沒有讀取源,它可以正常工作。當我嘗試從預製的pdf中讀取時,它會停止創建窗體/窗口小部件,但仍按預期方式添加段落。沒有錯誤給出。有誰明白爲什麼會發生這種情況?IText7僅在新文檔上創建窗體/窗口小部件

這裏是我運行代碼:

public class HelloWorld { 

    public static final String DEST = "sampleOutput.pdf"; 
    public static final String SRC = "sample.pdf"; 
    public static void main(String args[]) throws IOException { 
     File file = new File(DEST); 

     new HelloWorld().createPdf(SRC, DEST); 
    } 

    public void createPdf(String src, String dest) throws IOException { 
     //Initialize PDF reader and writer 
     PdfReader reader = new PdfReader(src); 
     PdfWriter writer = new PdfWriter(dest); 

     //Initialize PDF document 
     PdfDocument pdf = new PdfDocument(writer); //if i do (reader, writer) the widget isn't added to the first page anymore. 

     // Initialize document 
     Document document = new Document(pdf); 

     HelloWorld.addAcroForm(pdf, document); 

     //Close document 
     document.close(); 
    } 

    public static PdfAcroForm addAcroForm(PdfDocument pdf, Document doc) throws IOException { 
     Paragraph title = new Paragraph("Test Form") 
       .setTextAlignment(TextAlignment.CENTER) 
       .setFontSize(16); 
     doc.add(title); 
     doc.add(new Paragraph("Full name:").setFontSize(12)); 

     //Add acroform 
     PdfAcroForm form = PdfAcroForm.getAcroForm(doc.getPdfDocument(), true); 
     //Create text field 
     PdfTextFormField nameField = PdfFormField.createText(doc.getPdfDocument(), 
       new Rectangle(99, 753, 425, 15), "name", ""); 

     form.addField(nameField); 
     return form; 

    } 
} 
+0

首先:感謝您提供示例代碼。當人們給我們一個我們可以編譯測試的樣本時,回答這個問題就容易得多。我試過你的例子,我無法重現這個問題:當我嘗試你的代碼時,字段被正確添加。我正在使用iText 7.0.1和頁面大小爲A4的源文件。我們可以看看你的源文件嗎?也許頁面大小的定義是不同的。如果座標系的原點('(0,0)')不在左下角,您可能會遇到您描述的問題。 –

+0

@BrunoLowagie謝謝你的迴應。這裏是示例文件,看到任何會拋出此消息的東西? http://www.filedropper.com/sample_15 – Elliot

+0

@BrunoLowagie出發點的好主意。我玩弄了x和y座標,我想我只是把這個部件放在範圍之外。非常感激!期待更多地使用該工具。 – Elliot

回答

1

我適應您的代碼是這樣的:

public static PdfAcroForm addAcroForm(PdfDocument pdf, Document doc) throws IOException { 
    Paragraph title = new Paragraph("Test Form") 
      .setTextAlignment(TextAlignment.CENTER) 
      .setFontSize(16); 
    doc.add(title); 
    doc.add(new Paragraph("Full name:").setFontSize(12)); 

    PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true); 
    PdfTextFormField nameField = PdfFormField.createText(pdf, 
      new Rectangle(99, 525, 425, 15), "name", ""); 
    form.addField(nameField, pdf.getPage(1)); 
    return form; 
} 

你會注意到兩個變化:

  1. 我改變Y字段的偏移量(525而不是753)。現在該字段被添加到頁面的可見區域內。在您的代碼中,該字段已添加,但不可見。
  2. 我通過添加pdf.getPage(1)作爲addField()方法的第二個參數來定義在哪個頁面上需要添加字段。
+0

這是解決方案, 謝謝。我還有其他1個問題需要提交,並且非常感謝您的瞭解。我無法使用兩個引用相同表單值的小部件。當我將表單值更改爲獨立時,我只能看到兩個小部件。 – Elliot

相關問題