be able to start with pdf a/3 files as well

This commit is contained in:
Jochen Stärk
2017-09-01 17:39:45 +02:00
parent 5d3ad6f920
commit 0292cfc2a9
13 changed files with 331 additions and 855 deletions

View File

@@ -0,0 +1,38 @@
package org.mustangproject.ZUGFeRD;
import java.io.IOException;
import java.io.InputStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.xmpbox.XMPMetadata;
public interface IExporterFactory {
public ZUGFeRDExporter load(String pdfFilename) throws IOException;
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfBinary
* binary of a PDF/A1 compliant document
*/
public ZUGFeRDExporter load(byte[] pdfBinary) throws IOException;
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfSource
* source to read a PDF/A1 compliant document from
* @throws IOException
*/
public ZUGFeRDExporter load(InputStream pdfSource) throws IOException;
public void prepareDocument(PDDocument doc) throws IOException;
public void addXMP(XMPMetadata metadata);
public IExporterFactory setCreator(String creator);
public IExporterFactory setConformanceLevel(PDFAConformanceLevel newLevel);
public IExporterFactory setProducer(String producer) ;
public IExporterFactory ignorePDFAErrors();
public IExporterFactory setZUGFeRDConformanceLevel(ZUGFeRDConformanceLevel zugferdConformanceLevel);
public IExporterFactory setAttachZUGFeRDHeaders(final boolean attachZugferdHeaders);
}

View File

@@ -194,8 +194,8 @@ public class ZUGFeRDExporter implements Closeable {
doc = createPDFA1Factory()
.setProducer(producer)
.setCreator(creator)
.setAttachZugferdHeaders(attachZugferdHeaders)
.loadFromPDFA1(filename)
.setAttachZUGFeRDHeaders(attachZugferdHeaders)
.load(filename)
.doc;
return doc.getDocumentCatalog();
@@ -211,20 +211,20 @@ public class ZUGFeRDExporter implements Closeable {
doc = createPDFA1Factory()
.setProducer(producer)
.setCreator(creator)
.setAttachZugferdHeaders(attachZugferdHeaders)
.loadFromPDFA1(file)
.setAttachZUGFeRDHeaders(attachZugferdHeaders)
.load(file)
.doc;
return doc.getDocumentCatalog();
}
private ZUGFeRDExporterFromA1Factory createPDFA1Factory() {
private IExporterFactory createPDFA1Factory() {
ZUGFeRDExporterFromA1Factory factory = new ZUGFeRDExporterFromA1Factory();
if (ignoreA1Errors) {
factory.ignoreA1Errors();
factory.ignorePDFAErrors();
}
return factory
.setZugferdConformanceLevel(zUGFeRDConformanceLevel)
.setZUGFeRDConformanceLevel(zUGFeRDConformanceLevel)
.setConformanceLevel(conformanceLevel);
}

View File

@@ -1,126 +1,19 @@
package org.mustangproject.ZUGFeRD;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.preflight.PreflightDocument;
import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.parser.PreflightParser;
import org.apache.pdfbox.preflight.utils.ByteArrayDataSource;
import org.apache.pdfbox.util.Version;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.PDFAIdentificationSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.type.BadFieldValueException;
import org.apache.xmpbox.xml.XmpSerializer;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.xml.transform.TransformerException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.GregorianCalendar;
public class ZUGFeRDExporterFromA1Factory {
private boolean ignoreA1Errors = false;
private ZUGFeRDConformanceLevel zugferdConformanceLevel = ZUGFeRDConformanceLevel.EXTENDED;
private PDFAConformanceLevel conformanceLevel = PDFAConformanceLevel.UNICODE;
private String producer = "mustangproject";
private String creator = "mustangproject";
private boolean attachZugferdHeaders = true;
private static boolean includeXMPinOptionalXPacket=true;
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfFilename
* filename of an PDF/A1 compliant document
*/
public ZUGFeRDExporter loadFromPDFA1(String pdfFilename) throws IOException {
ensurePDFIsValidA1(new FileDataSource(pdfFilename));
PDDocument doc = PDDocument.load(new File(pdfFilename));
makePDFA3compliant(doc);
return new ZUGFeRDExporter(doc);
}
import javax.xml.transform.TransformerException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.xmpbox.type.BadFieldValueException;
public class ZUGFeRDExporterFromA1Factory extends ZUGFeRDExporterFromA3Factory implements IExporterFactory {
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfBinary
* binary of a PDF/A1 compliant document
* Make a PDF A/3 from the PDF A/1
*/
public ZUGFeRDExporter loadFromPDFA1(byte[] pdfBinary) throws IOException {
ensurePDFIsValidA1(new ByteArrayDataSource(new ByteArrayInputStream(pdfBinary)));
ZUGFeRDExporter zugFeRDExporter;
PDDocument doc = PDDocument.load(pdfBinary);
makePDFA3compliant(doc);
zugFeRDExporter = new ZUGFeRDExporter(doc);
return zugFeRDExporter;
}
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfSource
* source to read a PDF/A1 compliant document from
*/
public ZUGFeRDExporter loadFromPDFA1(InputStream pdfSource) throws IOException {
return loadFromPDFA1(readAllBytes(pdfSource));
}
private void ensurePDFIsValidA1(final DataSource dataSource) throws IOException {
if (!ignoreA1Errors && !isValidA1(dataSource)) {
throw new IOException("File is not a valid PDF/A-1 input file");
}
}
private static byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
IOUtils.copy(in, buffer);
return buffer.toByteArray();
}
private void makePDFA3compliant(PDDocument doc) throws IOException {
String fullProducer = producer + " (via mustangproject.org " + org.mustangproject.ZUGFeRD.Version.VERSION + ")";
PDDocumentCatalog cat = doc.getDocumentCatalog();
PDMetadata metadata = new PDMetadata(doc);
cat.setMetadata(metadata);
XMPMetadata xmp = XMPMetadata.createXMPMetadata();
PDFAIdentificationSchema pdfaid = new PDFAIdentificationSchema(xmp);
xmp.addSchema(pdfaid);
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.addCreator(creator);
XMPBasicSchema xsb = xmp.createAndAddXMPBasicSchema();
xsb.setCreatorTool(creator);
xsb.setCreateDate(GregorianCalendar.getInstance());
// PDDocumentInformation pdi=doc.getDocumentInformation();
PDDocumentInformation pdi = new PDDocumentInformation();
pdi.setProducer(fullProducer);
pdi.setAuthor(creator);
doc.setDocumentInformation(pdi);
AdobePDFSchema pdf = xmp.createAndAddAdobePDFSchema();
pdf.setProducer(fullProducer);
public void prepareDocument(PDDocument doc) throws IOException {
super.prepareDocument(doc);
/*
* // Mandatory: PDF/A3-a is tagged PDF which has to be expressed using a //
* MarkInfo dictionary (PDF A/3 Standard sec. 6.7.2.2) PDMarkInfo markinfo = new
@@ -159,132 +52,4 @@ public class ZUGFeRDExporterFromA1Factory {
}
}
private static byte[] serializeXmpMetadata(XMPMetadata xmpMetadata) throws TransformerException {
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
String prefix="";
String suffix="";
if (includeXMPinOptionalXPacket) {
prefix="<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>";
suffix="<?xpacket end=\"w\"?>";
}
try {
buffer.write(prefix.getBytes("UTF-8"));
serializer.serialize(xmpMetadata, buffer, false);
buffer.write(suffix.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buffer.toByteArray();
}
private static boolean isValidA1(DataSource dataSource) throws IOException {
return getA1ParserValidationResult(new PreflightParser(dataSource));
}
/**
* This will add both the RDF-indication which embedded file is Zugferd and the
* neccessary PDF/A schema extension description to be able to add this
* information to RDF
*
* @param metadata
*/
private void addXMP(XMPMetadata metadata) {
if (attachZugferdHeaders) {
XMPSchemaZugferd zf = new XMPSchemaZugferd(metadata, zugferdConformanceLevel);
metadata.addSchema(zf);
}
XMPSchemaPDFAExtensions pdfaex = new XMPSchemaPDFAExtensions(metadata, attachZugferdHeaders);
metadata.addSchema(pdfaex);
}
/**
* Sets the ZUGFeRD conformance level (override).
*
* @param zugferdConformanceLevel
* the new conformance level
*/
public ZUGFeRDExporterFromA1Factory setZugferdConformanceLevel(ZUGFeRDConformanceLevel zugferdConformanceLevel) {
this.zugferdConformanceLevel = zugferdConformanceLevel;
return this;
}
private static boolean getA1ParserValidationResult(PreflightParser parser) throws IOException {
/*
* Parse the PDF file with PreflightParser that inherits from the
* NonSequentialParser. Some additional controls are present to check a set of
* PDF/A requirements. (Stream length consistency, EOL after some Keyword...)
*/
parser.parse();
try (PreflightDocument document = parser.getPreflightDocument()) {
/*
* Once the syntax validation is done, the parser can provide a
* PreflightDocument (that inherits from PDDocument) This document process the
* end of PDF/A validation.
*/
document.validate();
// Get validation result
return document.getResult().isValid();
} catch (ValidationException e) {
/*
* the parse method can throw a SyntaxValidationException if the PDF file can't
* be parsed. In this case, the exception contains an instance of
* ValidationResult
*/
return false;
}
}
/**
* All files are PDF/A-3, setConformance refers to the level conformance.
*
* PDF/A-3 has three coformance levels, called "A", "U" and "B".
*
* PDF/A-3-B where B means only visually preservable, U -standard for Mustang-
* means visually and unicode preservable and A means full compliance, i.e.
* visually, unicode and structurally preservable and tagged PDF, i.e. useful
* metainformation for blind people.
*
* Feel free to pass "A" as new level if you know what you are doing :-)
*
*
*/
public ZUGFeRDExporterFromA1Factory setConformanceLevel(PDFAConformanceLevel newLevel) {
conformanceLevel = newLevel;
return this;
}
public ZUGFeRDExporterFromA1Factory ignoreA1Errors() {
this.ignoreA1Errors = true;
return this;
}
public ZUGFeRDExporterFromA1Factory setAttachZugferdHeaders(final boolean attachZugferdHeaders) {
this.attachZugferdHeaders = attachZugferdHeaders;
return this;
}
public ZUGFeRDExporterFromA1Factory setCreator(String creator) {
this.creator = creator;
return this;
}
public ZUGFeRDExporterFromA1Factory setProducer(String producer) {
this.producer = producer;
return this;
}
}

View File

@@ -0,0 +1,256 @@
package org.mustangproject.ZUGFeRD;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.preflight.PreflightDocument;
import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.parser.PreflightParser;
import org.apache.pdfbox.preflight.utils.ByteArrayDataSource;
import org.apache.pdfbox.util.Version;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.PDFAIdentificationSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.type.BadFieldValueException;
import org.apache.xmpbox.xml.XmpSerializer;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.xml.transform.TransformerException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.GregorianCalendar;
public class ZUGFeRDExporterFromA3Factory implements IExporterFactory {
protected boolean ignorePDFAErrors = false;
protected ZUGFeRDConformanceLevel zugferdConformanceLevel = ZUGFeRDConformanceLevel.EXTENDED;
protected PDFAConformanceLevel conformanceLevel = PDFAConformanceLevel.UNICODE;
protected String producer = "mustangproject";
protected String creator = "mustangproject";
protected boolean attachZugferdHeaders = true;
protected PDMetadata metadata = null;
protected PDFAIdentificationSchema pdfaid = null;
protected XMPMetadata xmp = null;
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfFilename
* filename of an PDF/A1 compliant document
*/
public ZUGFeRDExporter load(String pdfFilename) throws IOException {
ensurePDFIsValidPDFA(new FileDataSource(pdfFilename));
PDDocument doc = PDDocument.load(new File(pdfFilename));
prepareDocument(doc);
return new ZUGFeRDExporter(doc);
}
public void prepareDocument(PDDocument doc) throws IOException {
String fullProducer = producer + " (via mustangproject.org " + org.mustangproject.ZUGFeRD.Version.VERSION + ")";
PDDocumentCatalog cat = doc.getDocumentCatalog();
metadata = new PDMetadata(doc);
cat.setMetadata(metadata);
xmp = XMPMetadata.createXMPMetadata();
pdfaid = new PDFAIdentificationSchema(xmp);
xmp.addSchema(pdfaid);
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.addCreator(creator);
XMPBasicSchema xsb = xmp.createAndAddXMPBasicSchema();
xsb.setCreatorTool(creator);
xsb.setCreateDate(GregorianCalendar.getInstance());
// PDDocumentInformation pdi=doc.getDocumentInformation();
PDDocumentInformation pdi = new PDDocumentInformation();
pdi.setProducer(fullProducer);
pdi.setAuthor(creator);
doc.setDocumentInformation(pdi);
AdobePDFSchema pdf = xmp.createAndAddAdobePDFSchema();
pdf.setProducer(fullProducer);
}
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfBinary
* binary of a PDF/A1 compliant document
*/
public ZUGFeRDExporter load(byte[] pdfBinary) throws IOException {
ensurePDFIsValidPDFA(new ByteArrayDataSource(new ByteArrayInputStream(pdfBinary)));
ZUGFeRDExporter zugFeRDExporter;
PDDocument doc = PDDocument.load(pdfBinary);
prepareDocument(doc);
zugFeRDExporter = new ZUGFeRDExporter(doc);
return zugFeRDExporter;
}
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfSource
* source to read a PDF/A1 compliant document from
*/
public ZUGFeRDExporter load(InputStream pdfSource) throws IOException {
return load(readAllBytes(pdfSource));
}
private void ensurePDFIsValidPDFA(final DataSource dataSource) throws IOException {
if (!ignorePDFAErrors && !isValidA1(dataSource)) {
throw new IOException("File is not a valid PDF/A input file");
}
}
private static byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
IOUtils.copy(in, buffer);
return buffer.toByteArray();
}
public byte[] serializeXmpMetadata(XMPMetadata xmpMetadata) throws TransformerException {
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
String prefix="<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>";
String suffix="<?xpacket end=\"w\"?>";
try {
buffer.write(prefix.getBytes("UTF-8")); // see https://github.com/ZUGFeRD/mustangproject/issues/44
serializer.serialize(xmpMetadata, buffer, false);
buffer.write(suffix.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buffer.toByteArray();
}
private static boolean isValidA1(DataSource dataSource) throws IOException {
return getPDFAParserValidationResult(new PreflightParser(dataSource));
}
/**
* This will add both the RDF-indication which embedded file is Zugferd and the
* neccessary PDF/A schema extension description to be able to add this
* information to RDF
*
* @param metadata
*/
public void addXMP(XMPMetadata metadata) {
if (attachZugferdHeaders) {
XMPSchemaZugferd zf = new XMPSchemaZugferd(metadata, zugferdConformanceLevel);
metadata.addSchema(zf);
}
XMPSchemaPDFAExtensions pdfaex = new XMPSchemaPDFAExtensions(metadata, attachZugferdHeaders);
metadata.addSchema(pdfaex);
}
/**
* Sets the ZUGFeRD conformance level (override).
*
* @param zugferdConformanceLevel
* the new conformance level
*/
public IExporterFactory setZUGFeRDConformanceLevel(ZUGFeRDConformanceLevel zugferdConformanceLevel) {
this.zugferdConformanceLevel = zugferdConformanceLevel;
return this;
}
private static boolean getPDFAParserValidationResult(PreflightParser parser) throws IOException {
/*
* Parse the PDF file with PreflightParser that inherits from the
* NonSequentialParser. Some additional controls are present to check a set of
* PDF/A requirements. (Stream length consistency, EOL after some Keyword...)
*/
parser.parse();
try (PreflightDocument document = parser.getPreflightDocument()) {
/*
* Once the syntax validation is done, the parser can provide a
* PreflightDocument (that inherits from PDDocument) This document process the
* end of PDF/A validation.
*/
document.validate();
// Get validation result
return document.getResult().isValid();
} catch (ValidationException e) {
/*
* the parse method can throw a SyntaxValidationException if the PDF file can't
* be parsed. In this case, the exception contains an instance of
* ValidationResult
*/
return false;
}
}
/**
* All files are PDF/A-3, setConformance refers to the level conformance.
*
* PDF/A-3 has three coformance levels, called "A", "U" and "B".
*
* PDF/A-3-B where B means only visually preservable, U -standard for Mustang-
* means visually and unicode preservable and A means full compliance, i.e.
* visually, unicode and structurally preservable and tagged PDF, i.e. useful
* metainformation for blind people.
*
* Feel free to pass "A" as new level if you know what you are doing :-)
*
*
*/
public IExporterFactory setConformanceLevel(PDFAConformanceLevel newLevel) {
conformanceLevel = newLevel;
return this;
}
public IExporterFactory ignorePDFAErrors() {
this.ignorePDFAErrors = true;
return this;
}
public IExporterFactory setAttachZUGFeRDHeaders(final boolean attachZugferdHeaders) {
this.attachZugferdHeaders = attachZugferdHeaders;
return this;
}
public IExporterFactory setCreator(String creator) {
this.creator = creator;
return this;
}
public IExporterFactory setProducer(String producer) {
this.producer = producer;
return this;
}
}

View File

@@ -14,6 +14,7 @@ import javax.xml.transform.TransformerException;
import org.mustangproject.ZUGFeRD.ZUGFeRDExporter;
import org.mustangproject.ZUGFeRD.ZUGFeRDExporterFromA1Factory;
import org.mustangproject.ZUGFeRD.ZUGFeRDExporterFromA3Factory;
import org.mustangproject.ZUGFeRD.ZUGFeRDImporter;
import com.sanityinc.jargs.CmdLineParser;
@@ -43,7 +44,6 @@ public class Toecount {
+ "\t--extract= extract invoice.zugferd.pdf to ZUGFeRD-invoice.xml\r\n"
+ "\t--upgrade= upgrade ZUGFeRD-invoice.pdf to ZUGFeRD-2-invoice.xml\r\n"
+ "\t--a3only= upgrade from PDF/A1 to A3 only \r\n"
);
}
@@ -60,11 +60,6 @@ public class Toecount {
Option<Boolean> upgradeOption = parser.addBooleanOption('u', "upgrade");
Option<Boolean> a3onlyOption = parser.addBooleanOption('a', "a3only");
if (args.length == 0) {
printUsage();
System.exit(2);
}
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
@@ -93,7 +88,7 @@ public class Toecount {
printHelp();
}
if (((directoryName != null) && (directoryName.length() > 0)) || filesFromStdIn.booleanValue()) {
else if (((directoryName != null) && (directoryName.length() > 0)) || filesFromStdIn.booleanValue()) {
StatRun sr = new StatRun();
if (ignoreFileExt) {
@@ -147,19 +142,15 @@ public class Toecount {
* .loadFromPDFA1("invoice.pdf");
*/
try {
ZUGFeRDExporter ze = new ZUGFeRDExporter();
ze.PDFmakeA3compliant("./invoice.pdf", "Toecount", System.getProperty("user.name"), true);
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA3Factory().setProducer("Toecount").setCreator(System.getProperty("user.name")).load("./invoice.pdf");
ze.setZUGFeRDXMLData(Files.readAllBytes(Paths.get("./ZUGFeRD-invoice.xml")));
ze.PDFattachZugferdFile(null);
ze.export("invoice.ZUGFeRD.pdf");
} catch (IOException e) {
e.printStackTrace();
// } catch (JAXBException e) {
// e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
// } catch (JAXBException e) {
// e.printStackTrace();
}
System.out.println("Written to invoice.ZUGFeRD.pdf");
} else if (extractRequested) {
ZUGFeRDImporter zi = new ZUGFeRDImporter();
@@ -178,7 +169,8 @@ public class Toecount {
* .loadFromPDFA1("invoice.pdf");
*/
try {
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory().setAttachZugferdHeaders(false).loadFromPDFA1("./invoice.pdf");
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory().setAttachZUGFeRDHeaders(false)
.load("./invoice.pdf");
ze.export("invoice.a3.pdf");
} catch (IOException e) {
@@ -301,6 +293,11 @@ public class Toecount {
}
System.out.println("Written to ZUGFeRD-2-invoice.xml");
} else {
// no argument or argument unknown
printUsage();
System.exit(2);
}
}
}

View File

@@ -59,7 +59,7 @@ public class MustangReaderWriterCustomXMLTest extends TestCase {
.getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf");
ZUGFeRDExporter zea1 = new ZUGFeRDExporterFromA1Factory().setProducer("My Application").setCreator("Test")
.loadFromPDFA1(SOURCE_PDF);
.load(SOURCE_PDF);
String ownZUGFeRDXML = "<rsm:CrossIndustryDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ram=\"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12\" xmlns:udt=\"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15\" xmlns:rsm=\"urn:ferd:CrossIndustryDocument:invoice:1p0\">\n"
+ "<rsm:SpecifiedExchangedDocumentContext>\n" + "<ram:TestIndicator>\n"
+ "<udt:Indicator>false</udt:Indicator>\n" + "</ram:TestIndicator>\n"

View File

@@ -8,8 +8,6 @@ import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.transform.TransformerException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -405,12 +403,13 @@ public class MustangReaderWriterEdgeTest extends TestCase implements IZUGFeRDExp
// the writing part
try(InputStream SOURCE_PDF =
this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf");
this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505PDFA3.pdf");
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory()
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA3Factory()
.setProducer("My Application")
.setCreator(System.getProperty("user.name"))
.loadFromPDFA1(SOURCE_PDF)) {
.ignorePDFAErrors()
.load(SOURCE_PDF)) {
ze.PDFattachZugferdFile(this);
ze.export(TARGET_PDF);

View File

@@ -410,7 +410,7 @@ public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExporta
this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf");
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory()
.loadFromPDFA1(SOURCE_PDF)) {
.load(SOURCE_PDF)) {
ze.PDFattachZugferdFile(this);
ze.export(TARGET_PDF);
@@ -466,7 +466,7 @@ public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExporta
this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505PDF14.pdf");
ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory()
.loadFromPDFA1(SOURCE_PDF)) {
.load(SOURCE_PDF)) {
ze.PDFattachZugferdFile(this);
ze.export(TARGET_PDF);

View File

@@ -1,95 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.mustangproject.ZUGFeRD</groupId>
<artifactId>toecount</artifactId>
<version>0.2.0-SNAPSHOT</version>
<name>ZUGFeRD PDF checker</name>
<description>Shows statistics on how many PDFs in a directory are ZUGFeRD-compliant, allows to combine XML and PDF, extract XML from PDF and migrate XML from ZF1 to ZF2</description>
<repositories>
<repository>
<id>mustang-mvn-repo</id>
<url>https://raw.github.com/ZUGFeRD/mustangproject/mvn-repo/</url>
</repository>
<repository>
<id>sonatype-oss-public</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<!-- jaxb?
javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory not found
-->
<!-- >dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.5</version>
</dependency -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.5</version>
</dependency>
<dependency>
<groupId>org.mustangproject.ZUGFeRD</groupId>
<artifactId>mustang</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.sanityinc</groupId>
<artifactId>jargs</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>toecount.Toecount</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>toecount.Toecount</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<!-- http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven mvn clean compile assembly:single -->
<!-- or whatever version you use -->
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,73 +0,0 @@
package toecount;
import org.mustangproject.ZUGFeRD.ZUGFeRDImporter;
public class FileChecker {
String filename;
StatRun thisRun;
boolean isPDF=false;
public FileChecker(String filename, StatRun statistics) {
this.filename=filename;
thisRun=statistics;
thisRun.incFileCount();
String extension = "";
if (!thisRun.shallIgnoreFileExt()) {
int extIndex = filename.lastIndexOf(".");
if (extIndex >= 0) {
extension = filename.substring(extIndex).toLowerCase();
isPDF=extension.equals(".pdf");// alternative check for PDF: File starts with %PDF-
thisRun.incPDFCount();
}
} else {
thisRun.incPDFCount();
}
}
public boolean checkForZUGFeRD() {
if ((!isPDF)&&(!thisRun.shallIgnoreFileExt())) {
return false;
}
ZUGFeRDImporter zi=new ZUGFeRDImporter();
try {
zi.extract(filename);
if (zi.canParse()) {
thisRun.incZUGFeRDCount();
return true;
} else {
return false;
}
} catch (NullPointerException e) {
// something really rare happened -- corrupted ZF?
/***
* e.g. Exception in thread "main" java.lang.NullPointerException
at org.mustangproject.ZUGFeRD.ZUGFeRDImporter.extractLowLevel(ZUGFeRDImporter.java:90)
at org.mustangproject.ZUGFeRD.ZUGFeRDImporter.extract(ZUGFeRDImporter.java:64)
at toecount.FileChecker.checkForZUGFeRD(FileChecker.java:33)
at toecount.Toecount.main(Toecount.java:111)
*
*/
// Ignore nevertheless, most likely we're batch processing
return false;
} catch (Exception e2) {
/**
* probably thrown up from
AM org.apache.pdfbox.pdfparser.PDFParser parse, most likely
INFORMATION: Document is encrypted
but also other internal PDF errors possible like
..Okt 23, 2015 11:17:53 AM org.apache.pdfbox.pdfparser.XrefTrailerResolver setStartxref
*/
return false;
}
}
public boolean isPDF() {
return isPDF;
}
public String getOutputLine() {
return thisRun.getOutputLine();
}
}

View File

@@ -1,56 +0,0 @@
package toecount;
import static java.nio.file.FileVisitResult.CONTINUE;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class FileTraverser extends SimpleFileVisitor<Path> {
private StatRun thisRun;
public FileTraverser(StatRun statistics) {
this.thisRun=statistics;
}
/***
* check each file
*/
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
if (attr.isSymbolicLink()) {
// Not yet handled
} else if (attr.isRegularFile()) {
String filename = file.toString();
FileChecker fc = new FileChecker(filename, thisRun);
fc.checkForZUGFeRD();
System.out.print(fc.getOutputLine());
}
return CONTINUE;
}
/***
* for each directory
*/
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
// System.out.format("Directory: %s%n", dir);
thisRun.incDirCount();
return CONTINUE;
}
/***
* show errors like file permission stacktraces
*/
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}

View File

@@ -1,69 +0,0 @@
package toecount;
public class StatRun {
private int pdfCount = 0;
private int horseCount = 0;
private int fileCount = 0;
private int dirCount = 0;
private boolean checkFileExt=true;
public void ignoreFileExtension() {
checkFileExt=false;
}
public boolean shallIgnoreFileExt() {
return !checkFileExt;
}
public void incFileCount(){
fileCount++;
}
public void incPDFCount(){
pdfCount++;
}
public void incZUGFeRDCount(){
horseCount++;
}
public void incDirCount(){
dirCount++;
}
public int getFileCount(){
return fileCount;
}
public int getPDFCount(){
return pdfCount;
}
public int getZUGFeRDCount(){
return horseCount;
}
public int getDirCount(){
return dirCount;
}
/***
* returns final statistics
* @return
*/
public String getSummaryLine() {
return "\r\n===================================================================\r\n"+String.format(
"Files:\t%d\tDirs:\t%d\tPDF:\t%d\tZUGFeRD:\t%d\r\n",
getFileCount(), getDirCount(), getPDFCount(), getZUGFeRDCount());
}
/***
* show that something is happening
* @return String
*/
public String getOutputLine() {
return ".";
}
}

View File

@@ -1,286 +0,0 @@
package toecount;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import javax.xml.bind.JAXBException;
import javax.xml.transform.TransformerException;
import org.mustangproject.ZUGFeRD.ZUGFeRDExporter;
import org.mustangproject.ZUGFeRD.ZUGFeRDImporter;
import com.sanityinc.jargs.CmdLineParser;
import com.sanityinc.jargs.CmdLineParser.Option;
public class Toecount {
// build with: /opt/local/bin/mvn clean compile assembly:single
private static void printUsage() {
System.err.println(getUsage());
}
private static String getUsage() {
return "Usage: Toecount [-d,--directory] [-l,--listfromstdin] [-i,--ignorefileextension] | [-c,--combine] | [-e,--extract] | [-u,--upgrade] | [-h,--help]\r\n";
}
private static void printHelp() {
System.out.println("Mustangproject.org's Toecount 0.2.0 \r\n"
+ "A Apache Public License command line tool for statistics on PDF invoices with\r\n"
+ "ZUGFeRD Metadata (http://www.zugferd.org)\r\n" + "\r\n" + getUsage() + "Count operations"
+ "\t--directory= count ZUGFeRD files in directory to be scanned\r\n"
+ "\t\tIf it is a directory, it will recurse.\r\n"
+ "\t--listfromstdin=count ZUGFeRD files from a list of linefeed separated files on runtime.\r\n"
+ "\t\tIt will start once a blank line has been entered.\r\n"
+ "\t--ignorefileextension=if PDF files are counted check *.* instead of *.pdf files"
+ "Merge operations"
+ "\t--combine= combine ZUGFeRD-invoice.xml and invoice.pdf to invoice.zugferd.pdf\r\n"
+ "\t--extract= extract invoice.zugferd.pdf to ZUGFeRD-invoice.xml\r\n"
+ "\t--upgrade= upgrafe ZUGFeRD-invoice.pdf to ZUGFeRD-2-invoice.xml\r\n"
);
}
// /opt/local/bin/mvn clean compile assembly:single
public static void main(String[] args) {
CmdLineParser parser = new CmdLineParser();
Option<String> dirnameOption = parser.addStringOption('d', "directory");
Option<Boolean> filesFromStdInOption = parser.addBooleanOption('l', "listfromstdin");
Option<Boolean> ignoreFileExtOption = parser.addBooleanOption('i', "ignorefileextension");
Option<Boolean> combineOption = parser.addBooleanOption('c', "combine");
Option<Boolean> extractOption = parser.addBooleanOption('e', "extract");
Option<Boolean> helpOption = parser.addBooleanOption('h', "help");
Option<Boolean> upgradeOption = parser.addBooleanOption('u', "upgrade");
if (args.length == 0) {
printUsage();
System.exit(2);
}
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
System.err.println(e.getMessage());
printUsage();
System.exit(2);
}
String directoryName = parser.getOptionValue(dirnameOption);
Boolean filesFromStdIn = parser.getOptionValue(filesFromStdInOption, Boolean.FALSE);
Boolean combineRequested = parser.getOptionValue(combineOption, Boolean.FALSE);
Boolean extractRequested = parser.getOptionValue(extractOption, Boolean.FALSE);
Boolean helpRequested = parser.getOptionValue(helpOption, Boolean.FALSE);
Boolean upgradeRequested = parser.getOptionValue(upgradeOption, Boolean.FALSE);
Boolean ignoreFileExt = parser.getOptionValue(ignoreFileExtOption, Boolean.FALSE);
if (helpRequested) {
printHelp();
}
if (((directoryName != null) && (directoryName.length() > 0)) || filesFromStdIn.booleanValue()) {
StatRun sr = new StatRun();
if (ignoreFileExt) {
sr.ignoreFileExtension();
}
if (directoryName != null) {
Path startingDir = Paths.get(directoryName);
if (Files.isRegularFile(startingDir)) {
String filename = startingDir.toString();
FileChecker fc = new FileChecker(filename, sr);
fc.checkForZUGFeRD();
System.out.print(fc.getOutputLine());
} else if (Files.isDirectory(startingDir)) {
FileTraverser pf = new FileTraverser(sr);
try {
Files.walkFileTree(startingDir, pf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (filesFromStdIn) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
try {
while ((s = in.readLine()) != null && s.length() != 0) {
FileChecker fc = new FileChecker(s, sr);
fc.checkForZUGFeRD();
System.out.print(fc.getOutputLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(sr.getSummaryLine());
} else if (combineRequested) {
/*
* ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory()
* .setProducer("toecount") .setCreator(System.getProperty("user.name"))
* .loadFromPDFA1("invoice.pdf");
*/
try {
ZUGFeRDExporter ze = new ZUGFeRDExporter();
ze.PDFmakeA3compliant("./invoice.pdf", "Toecount", System.getProperty("user.name"), true);
ze.setZUGFeRDXMLData(Files.readAllBytes(Paths.get("./ZUGFeRD-invoice.xml")));
ze.PDFattachZugferdFile(null);
ze.export("invoice.ZUGFeRD.pdf");
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
System.out.println("Written to invoice.ZUGFeRD.pdf");
} else if (extractRequested) {
ZUGFeRDImporter zi = new ZUGFeRDImporter();
zi.extract("invoice.zugferd.pdf");
try {
Files.write(Paths.get("./ZUGFeRD-invoice.xml"), zi.getRawXML());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Written to ZUGFeRD-invoice.xml");
} else if (upgradeRequested) {
try {
String xml = new String(Files.readAllBytes(Paths.get("./ZUGFeRD-invoice.xml")), StandardCharsets.UTF_8);
// todo: attributes may also be in single quotes, this one hardcodedly expects
// double ones
xml = xml.replace("\"urn:ferd:CrossIndustryDocument:invoice:1p0",
"\"urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:13");
xml = xml.replace("urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12",
"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:20");
xml = xml.replace("urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15",
"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:20");
xml = xml.replace("rsm:CrossIndustryDocument", "rsm:CrossIndustryInvoice");
xml = xml.replace("rsm:SpecifiedExchangedDocumentContext", "rsm:CIExchangedDocumentContext");
xml = xml.replace("rsm:HeaderExchangedDocument", "rsm:CIIHExchangedDocument");
xml = xml.replace("SpecifiedSupplyChainTradeTransaction", "CIIHSupplyChainTradeTransaction");
xml = xml.replace("ram:GuidelineSpecifiedDocumentContextParameter",
"ram:GuidelineSpecifiedCIDocumentContextParameter");
xml = xml.replace("ram:IncludedNote", "ram:IncludedCINote");
xml = xml.replace("ram:ApplicableSupplyChainTradeAgreement",
"ram:ApplicableCIIHSupplyChainTradeAgreement");
xml = xml.replace("ram:SellerTradeParty", "ram:SellerCITradeParty");
xml = xml.replace("ram:BuyerTradeParty", "ram:BuyerCITradeParty");
xml = xml.replace("ram:ApplicableSupplyChainTradeDelivery",
"ram:ApplicableCIIHSupplyChainTradeDelivery");
xml = xml.replace("ram:ApplicableSupplyChainTradeSettlement",
"ram:ApplicableCIIHSupplyChainTradeSettlement");
xml = xml.replace("ram:IncludedSupplyChainTradeLineItem", "ram:IncludedCIILSupplyChainTradeLineItem");
xml = xml.replace("ram:AssociatedDocumentLineDocument", "ram:AssociatedCIILDocumentLineDocument");
xml = xml.replace("ram:SpecifiedSupplyChainTradeDelivery", "ram:SpecifiedCIILSupplyChainTradeDelivery");
xml = xml.replace("ram:SpecifiedSupplyChainTradeSettlement",
"ram:SpecifiedCIILSupplyChainTradeSettlement");
xml = xml.replace("ram:SpecifiedTradeProduct", "ram:SpecifiedCITradeProduct");
xml = xml.replace("ram:ActualDeliverySupplyChainEvent", "ram:ActualDeliveryCISupplyChainEvent");
xml = xml.replace("ram:SpecifiedTradeSettlementPaymentMeans",
"ram:SpecifiedCITradeSettlementPaymentMeans");
xml = xml.replace("ram:PayeePartyCreditorFinancialAccount", "ram:PayeePartyCICreditorFinancialAccount");
xml = xml.replace("ram:PayeeSpecifiedCreditorFinancialInstitution",
"ram:PayeeSpecifiedCICreditorFinancialInstitution");
xml = xml.replace("ram:ApplicableTradeTax", "ram:ApplicableCITradeTax");
xml = xml.replace("ram:ApplicablePercent", "ram:RateApplicablePercent");
xml = xml.replace("ram:PostalTradeAddress", "ram:PostalCITradeAddress");
xml = xml.replace("ram:ApplicableTradePaymentDiscountTerms",
"ram:ApplicableCITradePaymentDiscountTerms");
xml = xml.replace("ram:ApplicableProductCharacteristic", "ram:ApplicableCIProductCharacteristic");
xml = xml.replace("ram:ShipToTradeParty", "ram:ShipToCITradeParty");
xml = xml.replace("ram:ShipFromTradeParty", "ram:ShipFromCITradeParty");
xml = xml.replace("ram:ReceivableSpecifiedTradeAccountingAccount",
"ram:ReceivableSpecifiedCITradeAccountingAccount");
xml = xml.replace("ram:ContractReferencedDocument", "ram:ContractReferencedCIReferencedDocument");
// "ram:SpecifiedTradeAccountingAccount ram:SalesSpecifiedTradeAccountingAccount
// oder ReceivablesSpecifiedTradeAccountingAccount oder
// PurchaseSpecifiedTradeAccountingAccount
xml = xml.replace("ram:AdditionalReferencedDocument", "ram:AdditionalReferencedCIReferencedDocument");
xml = xml.replace("ram:TelephoneUniversalCommunication", "ram:TelephoneCIUniversalCommunication");
xml = xml.replace("ram:EmailURIUniversalCommunication", "ram:EmailURICIUniversalCommunication");
xml = xml.replace("ram:AdditionalReferencedDocument", "ram:AdditionalReferencedCIReferencedDocument");
xml = xml.replace("ram:IncludedReferencedProduct", "ram:IncludedReferencedProduct");
xml = xml.replace("ram:DefinedTradeContact", "ram:DefinedCITradeContact");
xml = xml.replace("ram:BillingSpecifiedPeriod", "ram:BillingCISpecifiedPeriod");
xml = xml.replace("ram:BuyerOrderReferencedDocument", "ram:BuyerOrderReferencedCIReferencedDocument");
xml = xml.replace("ram:DeliveryNoteReferencedDocument",
"ram:DeliveryNoteReferencedCIReferencedDocument");
xml = xml.replace("ram:SpecifiedTradeAllowanceCharge", "ram:SpecifiedCITradeAllowanceCharge");
xml = xml.replace("ram:SpecifiedLogisticsServiceCharge", "ram:SpecifiedCILogisticsServiceCharge");
xml = xml.replace("ram:AppliedTradeAllowanceCharge", "ram:AppliedCITradeAllowanceCharge");
xml = xml.replace("ram:InvoiceeTradeParty", "ram:InvoiceeCITradeParty");
xml = xml.replace("ram:CategoryTradeTax", "ram:CategoryCITradeTax");
xml = xml.replace("ram:SpecifiedTaxRegistration", "ram:SpecifiedCITaxRegistration");
xml = xml.replace("ram:PostalTradeAddress", "ram:PostalCITradeAddress");
xml = xml.replace("ram:SpecifiedTradePaymentTerms", "ram:SpecifiedCITradePaymentTerms");
xml = xml.replace("ram:SpecifiedSupplyChainTradeAgreement",
"ram:SpecifiedCIILSupplyChainTradeAgreement");
xml = xml.replace("ram:GrossPriceProductTradePrice", "ram:GrossPriceProductCITradePrice");
xml = xml.replace("ram:NetPriceProductTradePrice", "ram:NetPriceProductCITradePrice");
xml = xml.replaceAll("(?s)\\<ram:TestIndicator.*\\/ram:TestIndicator>", "");
// remove manually for the time being:
// xml=xml.replaceAll("ram:TestIndicator>(.*?)/ram:TestIndicator>", "");
// one ram:SpecifiedCIILTradeSettlementMonetarySummation will have to be
// ram:SpecifiedCIIHTradeSettlementMonetarySummation afterwards
String summationClose = "</ram:SpecifiedTradeSettlementMonetarySummation>";
int posFirstSummation = xml.indexOf(summationClose) + summationClose.length();
// if ram:SpecifiedTradeSettlementMonetarySummation were not found indexOf would
// return -1, therefore,
// to check if it
if (posFirstSummation > summationClose.length()) {
String xmlAfterFirstSummation = xml.substring(posFirstSummation);
String xmlBeforeIncludingFirstSummation = xml.substring(0, posFirstSummation);
// replace only once the header
xmlBeforeIncludingFirstSummation = xmlBeforeIncludingFirstSummation.replace(
"ram:SpecifiedTradeSettlementMonetarySummation",
"ram:SpecifiedCIIHTradeSettlementMonetarySummation");
// reconstruct the document now with a replaced first
// ram:SpecifiedTradeSettlementMonetarySummation to SpecifiedCIIH...
xml = xmlBeforeIncludingFirstSummation + xmlAfterFirstSummation;
}
// replace the rest of the ram:SpecifiedTradeSettlementMonetarySummation with
// the line value SpecifiedCIIL...
xml = xml.replace("ram:SpecifiedTradeSettlementMonetarySummation",
"ram:SpecifiedCIILTradeSettlementMonetarySummation");
// the rest of the ram:SpecifiedTradeSettlementMonetarySummation should be in
// ram:ApplicableSupplyChainTradeSettlement
// xml=xml.replaceAll(Pattern.quote("ram:SpecifiedTradeSettlementMonetarySummation"),
// "ram:SpecifiedCIILTradeSettlementMonetarySummation");
Files.write(Paths.get("./ZUGFeRD-2-invoice.xml"), xml.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Written to ZUGFeRD-2-invoice.xml");
}
}
}