Context
Attaching a file to an existing PDF with PdfPig’s PdfIncrementalUpdateBuilder (only in the 0.1.17-alpha nightlies so far; checked against 0.1.17-alpha-202611292238-b740a): the builder appends an incremental update, and AddEmbeddedFile adds the attachment. The goal was a PDF/A-3 file with an associated file (/AF, /AFRelationship), for example a hybrid e-invoice.
Documented
Embedded files are supported for PDF/A-3, where the builder also writes each file’s relationship and associates the file with the document. For an existing document, the PDF/A standard is taken from the document’s XMP metadata. (PdfPig README)
Observed
The PDF/A part is read when the update is built, so the call order does not matter. AddEmbeddedFile only validates and stores the file. Build() resolves the catalog, including one replaced with ReplaceObject in the same update, and reads pdfaid:part from its XMP. If that says 3, each file specification gets /AFRelationship and the catalog gets /AF. If the document declares no PDF/A part, the file is attached as a plain attachment, with no /AF and no error. Another part (1, 2, 4) makes Build() throw NotSupportedException.
So to make a carrier PDF that is not yet PDF/A-3 into one, replace its catalog with one whose /Metadata declares PDF/A-3. Before or after AddEmbeddedFile gives the same result (both orders tested):
var builder = new PdfIncrementalUpdateBuilder(document);var catalog = document.Structure.Catalog.CatalogDictionary .With(NameToken.Metadata, builder.AddObject(xmpStreamDeclaringPdfA3));builder.ReplaceObject(document.Structure.Trailer.Root, catalog);builder.AddEmbeddedFile("factur-x.xml", xml, new EmbeddedFileOptions{ MimeType = "text/xml", Relationship = AssociatedFileRelationship.Alternative,});var bytes = builder.Build();If /AF is missing from the output, check that the XMP the built catalog points to actually decodes and contains pdfaid:part = 3. Metadata that cannot be decoded or parsed as XML counts as “no PDF/A part” without an error.
The trailer /ID is random. As in PDFBox’s COSWriter, the builder keeps the first half of the previous /ID and sets the second half to Guid.NewGuid(). There is no option to set it, so the same input gives different bytes on every run. An option to set it is requested in UglyToad/PdfPig#1552. Until then, two ways to make output reproducible:
- Write the update’s trailer yourself, for example with PdfPig’s
TokenWriter, and derive/IDfrom a hash of the inputs. - Patch the generated
/IDhex digits in place with digits of the same length, so no offsets move.
When patching, note that a half of /ID copied from the carrier may be a literal string (…), not <hex>. Keep that half as it is.