使用 PDFBox 填写 PDF 表单
我有一个pdf文件,里面有一个表格。我正在尝试编写一个类,该类将从数据库中获取数据并自动填充表单中的字段。
我已经尝试过 ITextSharp,他们的定价超出了我的预算,尽管它与我的 pdf 完美配合。我需要一个免费的 pdf 解析器,它可以让我导入 pdf、设置数据并保存 PDF,最好保存到流中,这样我就可以从类中返回 Stream 对象,而不是将 pdf 保存到服务器。
我发现这个pdf阅读器但它不起作用。空引用错误很多,当我尝试“修复”它们时,它仍然找不到我的字段。
因此,我已经转向 PdfBox,因为文档说它可以操作 PDF,但是,我找不到任何示例。这是我到目前为止的代码。
var document = PDDocument.load(inputPdf);
var catalog = document.getDocumentCatalog();
var form = catalog.getAcroForm();
form.getField("MY_FIELD").setValue("Test Value");
document.save("some location on my hard drive");
document.close();
问题是 catalog.getAcroForm()
返回 null,因此我无法访问这些字段。有谁知道如何使用 PdfBox 更改字段值并将其保存回来?
编辑:
我确实找到了这个例子,这几乎就是我正在做的事情。只是我的 acroform 在 pdfbox 中为空。我知道那里有一个,因为 itextsharp 可以很好地把它拉出来。
I have a pdf with a form in it. I am trying to write a class that will take data from my database and automatically populate the fields in the form.
I have already tried ITextSharp and their pricing is out of my budget, even though it works perfectly fine with my pdf. I need a free pdf parser that will let me import the pdf, set the data, and save the PDF out, preferably to a stream so that I can return a Stream object from my class rather than saving the pdf to the server.
I found this pdf reader and it doesn't work. Null reference errors are abundant and when I tried to "fix" them, it still couldn't find my fields.
So, I have moved on to PdfBox, as the documentation says it can manipulate a PDF, however, I cannot find any examples. Here is the code I have so far.
var document = PDDocument.load(inputPdf);
var catalog = document.getDocumentCatalog();
var form = catalog.getAcroForm();
form.getField("MY_FIELD").setValue("Test Value");
document.save("some location on my hard drive");
document.close();
The problem is that catalog.getAcroForm()
is returning a null, so I can't access the fields. Does anyone know how I can use PdfBox to alter the field values and save the thing back out?
EDIT:
I did find this example, which is pretty much what I am doing. It's just that my acroform is null in pdfbox. I know there is one there because itextsharp can pull it out just fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你试过1.2.1版本吗?
http://pdfbox.apache.org/apidocs/overview-summary.html
Have you tried with the 1.2.1 version?
http://pdfbox.apache.org/apidocs/overview-summary.html