免费库将FDF导入PDF

时间:2013-06-24 12:54:58

标签: c# pdf fdf

我正在尝试通过将 FDF 中的数据保存到 PDFTemplate 中保存 PDF 文件,在我的 WPF < / strong>申请。

所以,情况是这样的。我有一个 PDFTemplate.pdf ,它作为模板并具有占位符(或字段)。现在我以编程方式生成此 FDF 文件,该文件又包含 PDFTemplate 所需的所有字段名称。此外,此 FDF 还包含 PDFTemaplte 的文件路径,因此在打开时,它知道要使用哪个 PDF

现在,当尝试双击 FDF 时,它会打开 Adob​​er Acrobat Reader 并显示 PDFTemplate 并填写数据但我无法使用“文件”菜单保存此文件,因为它表示此文件将在没有数据的情况下保存。

我想知道是否可以将 FDF 数据导入 PDF 并在不使用第三方组件的情况下保存。

另外,如果要做到这一点非常困难,那么可以解决的免费图书馆方法是什么呢?

我刚才意识到 iTextSharp 不适用于商业应用。

1 个答案:

答案 0 :(得分:2)

我已经能够使用另一个库 PDFSharp 来实现这一目标。

它有点类似于iTextSharp的工作原理,除了iTextSharp更好更容易使用的一些地方。我发布代码以防有人想要做类似的事情:

//Create a copy of the original PDF file from source 
//to the destination location
File.Copy(formLocation, outputFileNameAndPath, true);

//Open the newly created PDF file
using (var pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(
                    outputFileNameAndPath, 
                    PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify))
{
   //Get the fields from the PDF into which the data 
   //is supposed to be inserted
    var pdfFields = pdfDoc.AcroForm.Fields;

    //To allow appearance of the fields
    if (pdfDoc.AcroForm.Elements.ContainsKey("/NeedAppearances") == false)
    {
        pdfDoc.AcroForm.Elements.Add(
            "/NeedAppearances", 
            new PdfSharp.Pdf.PdfBoolean(true));
    }
    else
    {
        pdfDoc.AcroForm.Elements["/NeedAppearances"] = 
            new PdfSharp.Pdf.PdfBoolean(true);
    }

    //To set the readonly flags for fields to their original values
    bool flag = false;

    //Iterate through the fields from PDF
    for (int i = 0; i < pdfFields.Count(); i++)
    {
        try
        {
            //Get the current PDF field
            var pdfField = pdfFields[i];

            flag = pdfField.ReadOnly;

            //Check if it is readonly and make it false
            if (pdfField.ReadOnly)
            {
                pdfField.ReadOnly = false;
            }

            pdfField.Value = new PdfSharp.Pdf.PdfString(
                             fdfDataDictionary.Where(
                             p => p.Key == pdfField.Name)
                             .FirstOrDefault().Value);

            //Set the Readonly flag back to the field
            pdfField.ReadOnly = flag;
        }
        catch (Exception ex)
        {
            throw new Exception(ERROR_FILE_WRITE_FAILURE + ex.Message);
        }
    }

    //Save the PDF to the output destination
    pdfDoc.Save(outputFileNameAndPath);                
    pdfDoc.Close();
}