2013-07-09 63 views
2

試圖使用pdfbox來創建可以由用戶或計算機填寫的表單域。 到目前爲止,我的代碼如下所示:Re:pdfbox庫;有沒有人發現如何將文本字段添加到PDF?

PDDocument doc = new PDDDocument(); 
PDPage page = new PDPage(); 
doc.addPage(page) 
PDAcroForm = new PDAcroForm(doc) 
doc.documentCatalog.setAcroForm(acroForm) 
COSDictionary cosDict = new COSDictionary() 
PDTextbox textField = new PDTextbox(acroForm, cosDict) 
PDRectangle rect = new PDRectangle() 
rect.setLowerLeftX((float) 250) 
rect.setLowerLeftY((float) 125) 
rect.setUpperRightX((float) 500) 
rect.setUpperRightY((float) 75) 
textField.getWidget().setRectangle(rect) 
acroForm.getFields.add(textField) 
page.getAnnotations().add(textField) 
page.getAnnotations().add(textField.getWidget()) 

回答

5

我幾乎同樣的問題。我試圖將字段添加到包含表單的現有文檔。我想出了以下解決方案:

PDDocument doc = new PDDocument(); 
PDPage page = new PDPage(); 
doc.addPage(page); 
PDAcroForm acroForm = new PDAcroForm(doc); 
doc.getDocumentCatalog().setAcroForm(acroForm); 
COSDictionary cosDict = new COSDictionary(); 

COSArray rect = new COSArray(); 
rect.add(new COSFloat(250f)); // lower x boundary 
rect.add(new COSFloat(75f)); // lower y boundary 
rect.add(new COSFloat(500f)); // upper x boundary 
rect.add(new COSFloat(125f)); // upper y boundary 

cosDict.setItem(COSName.RECT, rect); 
cosDict.setItem(COSName.FT, COSName.getPDFName("Tx")); // Field Type 
cosDict.setItem(COSName.TYPE, COSName.ANNOT); 
cosDict.setItem(COSName.SUBTYPE, COSName.getPDFName("Widget")); 
cosDict.setItem(COSName.T, new COSString("yourFieldName")); 

PDTextbox textField = new PDTextbox(acroForm, cosDict); 

acroForm.getFields().add(textField); 
page.getAnnotations().add(textField.getWidget()); 

我認爲問題是小部件不寫入字典的textField。

相關問題