etmcm
etmcm

Reputation: 1

Itext7 - How to add embedded file with f and uf key to pdfa

im having a hard time adding a zugferd xml file as a fileattachment to a pdf file.

static void EmbedFile(PdfADocument pdfDoc, string filePath)
{
    byte[] fileContent = File.ReadAllBytes(filePath);

    PdfDictionary dict = new PdfDictionary();
    dict.Put(PdfName.F, new PdfString(filePath));
    dict.Put(PdfName.UF, new PdfString(filePath, PdfEncodings.UNICODE_BIG));

    PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, fileContent, "ZUGFeRD XML File",  PdfName.Alternative);
        
    pdfDoc.AddFileAttachment("zugferd.xml", fileSpec);

}
static void ConvertToPdfA3b(string sourcePdfPath, string outputPdfPath, string iccProfilePath, string zugferdXmlFilePath)
{
    if (!File.Exists(iccProfilePath))
    {
        throw new FileNotFoundException("ICC profile not found at " + iccProfilePath);
    }

    using (iText.Kernel.Pdf.PdfWriter writer = new iText.Kernel.Pdf.PdfWriter(outputPdfPath))
    {
        using (PdfADocument pdfADoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB_ICC_v4_Appearance",
                new FileStream(iccProfilePath, FileMode.Open, FileAccess.Read))))
        {
            pdfADoc.GetDocumentInfo().SetTitle("PDF/A-3b Document");
            pdfADoc.GetDocumentInfo().SetAuthor("Author Name");
            pdfADoc.GetDocumentInfo().SetSubject("Subject of the Document");
     
            XMPMeta xmpMeta = XMPMetaFactory.Create();
            xmpMeta.SetProperty(XMPConst.NS_DC, DublinCoreProperties.FORMAT, "application/pdf");
            xmpMeta.SetProperty(XMPConst.NS_DC, DublinCoreProperties.DESCRIPTION, "Converted to PDF/A-3b");

            PdfCatalog catalog = pdfADoc.GetCatalog();

            PdfDictionary markInfo = catalog.GetPdfObject().GetAsDictionary(PdfName.MarkInfo);
            if (markInfo == null)
            {
                markInfo = new PdfDictionary();
                catalog.GetPdfObject().Put(PdfName.MarkInfo, markInfo);
            }
            markInfo.Put(PdfName.Marked, iText.Kernel.Pdf.PdfBoolean.TRUE);


            // Read the source PDF file and copy pages to the PdfADocument
            using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(new iText.Kernel.Pdf.PdfReader(sourcePdfPath)))
            {
                pdfDoc.CopyPagesTo(1, pdfDoc.GetNumberOfPages(), pdfADoc);
            }

            pdfADoc.SetXmpMetadata(xmpMeta);
            EmbedFile(pdfADoc, zugferdXmlFilePath);

            // Close the document to save changes
            pdfADoc.Close();
        }
    }
}

I am loading a file and adding the keys to the dictionary. But im getting the exception : iText.Pdfa.Exceptions.PdfAConformanceException: "File specification dictionary shall contain f key and uf key"

Upvotes: 0

Views: 246

Answers (0)

Related Questions