Streuner
Streuner

Reputation: 125

How to attach ZUGFeRD-XML to a PDF with perl?

I need to create a PDF/A 3b-document with an XML attached to it like it's declared in ZUGFeRD. For this purpose I wrote myself a perl-script which can create the XML-file as a string and attach it to a PDF. I followed the tutorial of the pdflib-cookbook, but I never get my XML to be 100% attached to the PDF. I see it under attached files, and I can save it from there to my filesystem, but if I check the PDF with an editor I just see the XMP-Metadata and not my XML.

I guess I need to attach the XML as an Embedded File Stream or something like that, but I'm not quite sure if I'm missing something in my code or I just need to add it in another way.

This is my XMP-File:

<!--

PDFlib GmbH 2013-2014

Sample ZUGFeRD XMP with the required PDF/A extension schema description
for the XMP properties of the ZUGFeRD schema and the actual ZUGFeRD properties.

Schema name: ZUGFeRD Schema
Preferred schema namespace prefix: zf
Schema namespace URI: urn:ferd:pdfa:CrossIndustryDocument:invoice:1p0#

Notes on the ZUGFeRD schema namespace URI:

- The use of mixed upper/lowercase in "CrossIndustryDocument" conforms to
  the ZUGFeRD 1.0 specification. The PDF samples distributed with the
  ZUGFeRD 1.0 info package use all-lowercase spelling "crossindustrydocument"
  which is not correct since it violates the ZUGFeRD specification.

- The required trailing "#" character is missing in the comment in the
  ZUGFeRD 1.0 extension schema description which is included in the ZUGFeRD
  specification, but it is correctly present in the actual XMP.


Based on the ZUGFeRD 1.0 package (published 2014-06 on www.ferd-net.de)
which is Copyright AWV e.V. 2014.


2014-07-01 (based on ZUGFeRD 1.0)
Adjustments for ZUGFeRD 1.0:
- updated header comments
- switched to new namespace URI
- adjusted property descriptions in the extension schema descriptions

2013-06-19 (based on ZUGFeRD RC)
Added a trailing hash character "#" to the "zf" namespace name as required
by the XMP 2005 specification which is referenced in PDF/A-2 and PDF/A-3.
Without this change Acrobat XI Preflight validation for PDF/A-3 complains
"Extension schema present but not valid"

2013-06-19
Singled out the zf properties into a separate rdf:Description node to work
around bug #4433 in PDFlib 9.0.0 which has been fixed in PDFlib 9.0.1.

-->
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<!--  The actual ZUGFeRD properties; adjust if required  -->
<rdf:Description xmlns:zf="urn:ferd:pdfa:CrossIndustryDocument:invoice:1p0#" rdf:about="">
<zf:ConformanceLevel>BASIC</zf:ConformanceLevel>
<zf:DocumentFileName>ZUGFeRD-invoice.xml</zf:DocumentFileName>
<zf:DocumentType>INVOICE</zf:DocumentType>
<zf:Version>1.0</zf:Version>
</rdf:Description>
<!--
 PDF/A extension schema description for the ZUGFeRD schema.
     It is crucial for PDF/A-3 conformance. Don't touch! 
-->
<rdf:Description xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#" rdf:about="">
<pdfaExtension:schemas>
<rdf:Bag>
<rdf:li rdf:parseType="Resource">
<pdfaSchema:schema>ZUGFeRD PDFA Extension Schema</pdfaSchema:schema>
<pdfaSchema:namespaceURI>urn:ferd:pdfa:CrossIndustryDocument:invoice:1p0#</pdfaSchema:namespaceURI>
<pdfaSchema:prefix>zf</pdfaSchema:prefix>
<pdfaSchema:property>
<rdf:Seq>
<rdf:li rdf:parseType="Resource">
<pdfaProperty:name>DocumentFileName</pdfaProperty:name>
<pdfaProperty:valueType>Text</pdfaProperty:valueType>
<pdfaProperty:category>external</pdfaProperty:category>
<pdfaProperty:description>name of the embedded XML invoice file</pdfaProperty:description>
</rdf:li>
<rdf:li rdf:parseType="Resource">
<pdfaProperty:name>DocumentType</pdfaProperty:name>
<pdfaProperty:valueType>Text</pdfaProperty:valueType>
<pdfaProperty:category>external</pdfaProperty:category>
<pdfaProperty:description>INVOICE</pdfaProperty:description>
</rdf:li>
<rdf:li rdf:parseType="Resource">
<pdfaProperty:name>Version</pdfaProperty:name>
<pdfaProperty:valueType>Text</pdfaProperty:valueType>
<pdfaProperty:category>external</pdfaProperty:category>
<pdfaProperty:description>The actual version of the ZUGFeRD XML schema</pdfaProperty:description>
</rdf:li>
<rdf:li rdf:parseType="Resource">
<pdfaProperty:name>ConformanceLevel</pdfaProperty:name>
<pdfaProperty:valueType>Text</pdfaProperty:valueType>
<pdfaProperty:category>external</pdfaProperty:category>
<pdfaProperty:description>The conformance level of the embedded ZUGFeRD data</pdfaProperty:description>
</rdf:li>
</rdf:Seq>
</pdfaSchema:property>
</rdf:li>
</rdf:Bag>
</pdfaExtension:schemas>
</rdf:Description>
</rdf:RDF>

This is my created XML-String:

    Zweck des Forums für elektronische Rechnungen bei der AWV e.V („FeRD“) ist u.a. die Schaffung und Spezifizierung
    eines offenen Datenformats für strukturierten elektronischen Datenaustausch auf der Grundlage offener und nicht
    diskriminierender, standardisierter Technologien („ZUGFeRD Datenformat“)

    Das ZUGFeRD Datenformat wird nach Maßgabe des FeRD sowohl Unternehmen als auch der öffentlichen Verwaltung
    frei zugänglich gemacht. Hierfür bietet FeRD allen Unternehmen und Organisationen der öffentlichen Verwaltung eine
    Lizenz für die Nutzung des urheberrechtlich geschützten ZUGFeRD-Datenformats zu fairen, sachgerechten und nicht
    diskriminierenden Bedingungen an.

    Die Spezifikation des FeRD zur Implementierung des ZUGFeRD Datenformats ist in ihrer jeweils geltenden Fassung
    abrufbar unter www.ferd-net.de.

    Im Einzelnen schließt die Nutzungsgewährung ein:
    =====================================

    FeRD räumt eine Lizenz für die Nutzung des urheberrechtlich geschützten ZUGFeRD Datenformats in der jeweils
    geltenden und akzeptierten Fassung (www.ferd-net.de) ein.
    Die Lizenz beinhaltet ein unwiderrufliches Nutzungsrecht einschließlich des Rechts der Weiterentwicklung,
    Weiterbearbeitung und Verbindung mit anderen Produkten.
    Die Lizenz gilt insbesondere für die Entwicklung, die Gestaltung, die Herstellung, den Verkauf, die Nutzung oder
    anderweitige Verwendung des ZUGFeRD Datenformats für Hardware- und/oder Softwareprodukte sowie sonstige
    Anwendungen und Dienste.
    Diese Lizenz schließt nicht die wesentlichen Patente der Mitglieder von FeRD ein. Als wesentliche Patente sind Patente
    und Patentanmeldungen weltweit zu verstehen, die einen oder mehrere Patentansprüche beinhalten, bei denen es sich um
    notwendige Ansprüche handelt. Notwendige Ansprüche sind lediglich jene Ansprüche der Wesentlichen Patente, die durch
    die Implementierung des ZUGFeRD Datenformats notwendigerweise verletzt würden.
    Der Lizenznehmer ist berechtigt, seinen jeweiligen Konzerngesellschaften ein unbefristetes, weltweites, nicht übertragbares,
    unwiderrufliches Nutzungsrecht einschließlich des Rechts der Weiterentwicklung, Weiterbearbeitung und Verbindung mit
    anderen Produkten einzuräumen.

    Die Lizenz wird kostenfrei zur Verfügung gestellt.

    Außer im Falle vorsätzlichen Verschuldens oder grober Fahrlässigkeit haftet FeRD weder für Nutzungsausfall, entgangenen
    Gewinn, Datenverlust, Kommunikationsverlust, Einnahmeausfall, Vertragseinbußen, Geschäftsausfall oder für Kosten,
    Schäden, Verluste oder Haftpflichten im Zusammenhang mit einer Unterbrechung der Geschäftstätigkeit, noch für konkrete,
    beiläufig entstandene, mittelbare Schäden, Straf- oder Folgeschäden und zwar auch dann nicht, wenn die Möglichkeit der
    Kosten, Verluste bzw. Schäden hätte normalerweise vorhergesehen werden können.-->
    <rsm:CrossIndustryDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <rsm:SpecifiedExchangedDocumentContext>
        <ram:GuidelineSpecifiedDocumentContextParameter>
          <ram:ID>urn:ferd:pdfa:CrossIndustryDocument:invoice:1p0#</ram:ID>
        </ram:GuidelineSpecifiedDocumentContextParameter>
      </rsm:SpecifiedExchangedDocumentContext>
      <rsm:HeaderExchangedDocument>
        <ram:TypeCode>380</ram:TypeCode>
        <ram:ID>2012-12345</ram:ID>
        <ram:Name>INVOICE</ram:Name>
        <ram:IssueDateTime>
          <udt:DateTimeString format="102">20160503</udt:DateTimeString>
        </ram:IssueDateTime>
      </rsm:HeaderExchangedDocument>
      <rsm:SpecifiedSupplyChainTradeTransaction>
        <ram:ApplicableSupplyChainTradeAgreement>
          <ram:SellerTradeParty>
            <ram:Name>Verkäufer AG</ram:Name>
          </ram:SellerTradeParty>
          <ram:BuyerTradeParty>
            <ram:Name>Käufer GmbH</ram:Name>
          </ram:BuyerTradeParty>
        </ram:ApplicableSupplyChainTradeAgreement>
        <ram:ApplicableSupplyChainTradeDelivery>
          <ram:ActualDeliverySupplyChainEvent>
            <ram:OccurrenceDateTime>
              <udt:DateTimeString format="102">20161103</udt:DateTimeString>
            </ram:OccurrenceDateTime>
          </ram:ActualDeliverySupplyChainEvent>
        </ram:ApplicableSupplyChainTradeDelivery>
      </rsm:SpecifiedSupplyChainTradeTransaction>
      <ram:ApplicableSupplyChainTradeSettlement>
        <ram:SpecifiedTradeSettlementPaymentMeans>
          <ram:ID schemeAgencyID="123456">ABCD</ram:ID>
          <ram:PayeePartyCreditorFinancialAccount>
            <ram:IBANID>DE123 12312 12312 1231231</ram:IBANID>
            <ram:AccountName>BigBoss</ram:AccountName>
          </ram:PayeePartyCreditorFinancialAccount>
          <ram:PayeeSpecifiedCreditorFinancialInstitution>
            <ram:BICID>WELADE9999999</ram:BICID>
          </ram:PayeeSpecifiedCreditorFinancialInstitution>
        </ram:SpecifiedTradeSettlementPaymentMeans>
        <ram:AcclicableTradeTax>
          <ram:CalculatedAmount currencyID="EUR">123.22</ram:CalculatedAmount>
          <ram:TypeCode>VAT</ram:TypeCode>
          <ram:ApplicablePercent>0.19</ram:ApplicablePercent>
        </ram:AcclicableTradeTax>
        <ram:AcclicableTradeTax>
          <ram:TaxBasisTotalAmount currencyID="EUR">120</ram:TaxBasisTotalAmount>
          <ram:LineTotalAmount currencyID="EUR">111</ram:LineTotalAmount>
          <ram:ChargeTotalAmount currencyID="EUR">20</ram:ChargeTotalAmount>
          <ram:AllowanceTotalAmount currencyID="EUR">15</ram:AllowanceTotalAmount>
          <ram:TaxBasisTotalAmount currencyID="EUR">11</ram:TaxBasisTotalAmount>
          <ram:TaxTotalAmount currencyID="EUR">111</ram:TaxTotalAmount>
          <ram:GrandTotalAmount currencyID="EUR">1234.11</ram:GrandTotalAmount>
        </ram:AcclicableTradeTax>
        <ram:InvoiceCurrencyCode>EUR</ram:InvoiceCurrencyCode>
      </ram:ApplicableSupplyChainTradeSettlement>
      <ram:IncludedSupplyChainTradeLineItem>
        <ram:SpecifiedSupplyChainTradeDelivery>
          <ram:BilledQuantity unitCode="KG">5</ram:BilledQuantity>
        </ram:SpecifiedSupplyChainTradeDelivery>
        <ram:SpecifiedTradeProduct>
          <ram:Name>Foo</ram:Name>
        </ram:SpecifiedTradeProduct>
      </ram:IncludedSupplyChainTradeLineItem>
      <ram:IncludedSupplyChainTradeLineItem>
        <ram:SpecifiedSupplyChainTradeDelivery>
          <ram:BilledQuantity unitCode="Liter">3</ram:BilledQuantity>
        </ram:SpecifiedSupplyChainTradeDelivery>
        <ram:SpecifiedTradeProduct>
          <ram:Name>Bar</ram:Name>
        </ram:SpecifiedTradeProduct>
      </ram:IncludedSupplyChainTradeLineItem>
      <ram:IncludedSupplyChainTradeLineItem>
        <ram:SpecifiedSupplyChainTradeDelivery>
          <ram:BilledQuantity unitCode="Stück">15</ram:BilledQuantity>
        </ram:SpecifiedSupplyChainTradeDelivery>
        <ram:SpecifiedTradeProduct>
          <ram:Name>FooBar</ram:Name>
        </ram:SpecifiedTradeProduct>
      </ram:IncludedSupplyChainTradeLineItem>
    </rsm:CrossIndustryDocument>

This is my perl-code to attach the XMP and XML to the file: use pdflib_pl;

    my $pdf = PDF_new();

    PDF_set_parameter($pdf, "textformat", "utf8");
    PDF_set_parameter($pdf, "SearchPath", "/usr/share/htmldoc/fonts");
    PDF_set_parameter($pdf, "FontAFM", "Helvetica=Helvetica.afm");
    PDF_set_parameter($pdf, "FontOutline", "Helvetica=Helvetica.pfa");

    my $font = PDF_load_font($pdf, "Helvetica", "unicode", "embedding=true");

    PDF_begin_document($pdf,'test.pdf', "pdfa=PDF/A-3b metadata={filename=zugferd/ZUGFeRD-invoice.xmp}");
    PDF_load_iccprofile($pdf, "sRGB", "usage=outputintent");

    # At this point I create the XML-File I attached to this question
    my $xmlData = CreateXmlData();

    PDF_create_pvf($pdf, '/pvf/ZUGFeRD-invoice.xml', $xmlData, "");

    my $xml_asset = PDF_load_asset($pdf,
                                   "Attachment",
                                   '/pvf/ZUGFeRD-invoice.xml',
                                   "mimetype=text/xml description={Rechnungsdaten im Zugferd-Xml-Format} relationship=Alternative documentattachment=true");

    PDF_begin_page($pdf, 595, 842);
    PDF_setfont($pdf, $font, 12);
    PDF_fit_textline($pdf, 'test', 400, 600, "boxsize={50 20}");
    PDF_end_page($pdf);

    PDF_end_document($pdf, "associatedfiles={" . $xml_asset . "} metadata={filename=zugferd/ZUGFeRD-invoice.xmp}");
    PDF_delete_pvf($pdf, '/pvf/ZUGFeRD-invoice.xml');

    PDF_end_document($pdf, "associatedfiles={" . $xml_asset . "} metadata={filename=zugferd/ZUGFeRD-invoice.xmp}");
    PDF_delete_pvf($pdf, $virtualXml);

Upvotes: 3

Views: 1445

Answers (1)

Rainer
Rainer

Reputation: 2185

your code is incomplete. You should create at least a single empty page, (PDF_begin_page_ext() / PDF_end_page_ext() before you load the asset and close the document. But preferable you should add the visual content of the invoice or import the PDF pages from an PDF/A document (as the linked cookbook sample do)

For debugging purpose, I would suggest to set errorpolicy to exception at the beginning of your script.

 PDF_set_parameter($pdf, "errorpolicy", "exception");

in this case, you would get an exception, as soon an error happens.

Hope this helps.

Upvotes: 3

Related Questions