【发布时间】:2013-11-21 16:48:58
【问题描述】:
我正在从在 LibreOffice 中创建的现有模板生成新的 PDF。它包含一个文本框。
代码编译并成功将 PDF 保存到新文件后,如果我在 Acrobat Reader XI 中打开新创建的文档,它会正确呈现,但是,即使我不修改最终文档,在关闭文档时,它会询问“是否要在关闭前保存对“filename.pdf”的更改?”
我已阅读 StackOverflow 及其官方网站 (iTextSharp) 上的其他帖子,并找到了一个解决方案,这可能是我以错误的方式实施。
public string spdftemplate = @"C:\test\input.pdf";
public string newFile = @"C:\test\output.pdf";
private void FillFormsProperly()
{
PdfReader reader = new PdfReader(spdftemplate);
byte[] bytes;
using (MemoryStream ms = new MemoryStream())
{
PdfStamper stamper = new PdfStamper(reader, ms);
#region ForTesting
//PdfContentByte cb = stamper.GetOverContent(1);
//ColumnText ct = new ColumnText(cb);
//ct.SetSimpleColumn(100, 100, 500, 200);
//ct.AddElement(new Paragraph("This was added using ColumnText"));
//ct.Go();
#endregion ForTesting
AcroFields pdfFormFields = stamper.AcroFields;
foreach (DictionaryEntry de in reader.AcroFields.Fields)
{
pdfFormFields.SetField(de.Key.ToString(), "test"); //"Text Box 1"
}
//string sTmp = "W-4 Completed for " + pdfFormFields.GetField("Text Box 1");
//MessageBox.Show(sTmp, "Finished");
//Flush the PdfStamper's buffer
stamper.FormFlattening = true;
stamper.Close();
//Get the raw bytes of the PDF
bytes = ms.ToArray();
}
//Do whatever you want with the bytes
//Below I'm writing them to disk
using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
}
}
我找到的最佳答案是:creating a pdf from a template in itextsharp and outputting as content disposition.
以上代码是我的(或多或少复制粘贴)实现。
很明显文件已损坏(但仍然可读),我该如何解决这个问题?
【问题讨论】:
-
如果需要,我可以附上模板。
-
请同时提供输入模板和输出文档。
-
看来LibreOffice有罪,输入PDF也提示保存文件对话框。
标签: c# .net pdf itextsharp