update command lines for xml to pdf

This commit is contained in:
jstaerk
2023-09-11 11:33:02 +02:00
parent 5bc13c01eb
commit b935ab1e19

View File

@@ -102,6 +102,9 @@ public class Main {
+ " [--language <lang>]: set output lang (en, fr or de)\n" + " [--language <lang>]: set output lang (en, fr or de)\n"
+ " [--source <filename>]: set input XML file\n" + " [--source <filename>]: set input XML file\n"
+ " [--out <filename>]: set output HTML file\n" + " [--out <filename>]: set output HTML file\n"
+ " --action pdf convert XML to PDF \n"
+ " [--source <filename>]: set input XML file\n"
+ " [--out <filename>]: set output PDF file\n"
; ;
} }
@@ -115,15 +118,11 @@ public class Main {
* Asks the user (repeatedly, if neccessary) on the command line for a String * Asks the user (repeatedly, if neccessary) on the command line for a String
* (offering a defaultValue) conforming to a Regex pattern * (offering a defaultValue) conforming to a Regex pattern
* *
* @param prompt * @param prompt the question to be asked to the user
* the question to be asked to the user * @param defaultValue the default return value if user hits enter
* @param defaultValue * @param pattern a regex of acceptable values
* the default return value if user hits enter
* @param pattern
* a regex of acceptable values
* @return the user answer conforming to pattern * @return the user answer conforming to pattern
* @throws Exception * @throws Exception if pattern not compielable or IOexception on input
* if pattern not compielable or IOexception on input
*/ */
protected static String getStringFromUser(String prompt, String defaultValue, String pattern) throws Exception { protected static String getStringFromUser(String prompt, String defaultValue, String pattern) throws Exception {
String input = ""; String input = "";
@@ -135,7 +134,7 @@ public class Main {
// for a more sophisticated dialogue maybe https://github.com/mabe02/lanterna/ // for a more sophisticated dialogue maybe https://github.com/mabe02/lanterna/
// could be taken into account // could be taken into account
System.out.print(prompt + " (default: " + defaultValue + ")"); System.out.print(prompt + " (default: " + defaultValue + ")");
if ((!firstInput)&&(pattern.length()>0)) { if ((!firstInput) && (pattern.length() > 0)) {
System.out.print("\n(allowed pattern: " + pattern + ")"); System.out.print("\n(allowed pattern: " + pattern + ")");
} }
@@ -187,17 +186,17 @@ public class Main {
if (selectedName.isEmpty()) { if (selectedName.isEmpty()) {
// pressed return without entering anything // pressed return without entering anything
if(defaultFilename.isEmpty()) { if (defaultFilename.isEmpty()) {
return ""; //no default -> this is an optional filename return ""; //no default -> this is an optional filename
} }
selectedName = defaultFilename; selectedName = defaultFilename;
} }
boolean hasCorrectExtension=false; boolean hasCorrectExtension = false;
String[] expectedExtensions=expectedExtension.split("\\|"); String[] expectedExtensions = expectedExtension.split("\\|");
for (String currentExtension: expectedExtensions) { for (String currentExtension : expectedExtensions) {
if (selectedName.toLowerCase().endsWith(currentExtension.toLowerCase())) { if (selectedName.toLowerCase().endsWith(currentExtension.toLowerCase())) {
hasCorrectExtension=true; hasCorrectExtension = true;
break; break;
} }
} }
@@ -242,6 +241,7 @@ public class Main {
return selectedName; return selectedName;
} }
private static void performUpgrade(String xmlName, String outName) throws IOException, TransformerException { private static void performUpgrade(String xmlName, String outName) throws IOException, TransformerException {
// Get params from user if not already defined // Get params from user if not already defined
@@ -330,6 +330,7 @@ public class Main {
// return result.toString(StandardCharsets.UTF_8); // return result.toString(StandardCharsets.UTF_8);
} }
/*** /***
* the main function of the commandline tool... * the main function of the commandline tool...
* @param args the commandline args, see also https://www.mustangproject.org/commandline/#verbose * @param args the commandline args, see also https://www.mustangproject.org/commandline/#verbose
@@ -341,25 +342,25 @@ public class Main {
// create Options object // create Options object
Options options = new Options(); Options options = new Options();
options.addOption(new Option("h", "help",false, "display usage")); options.addOption(new Option("h", "help", false, "display usage"));
options.addOption(new Option("a", "action",true, "which action to perform")); options.addOption(new Option("a", "action", true, "which action to perform"));
options.addOption(new Option("f", "format",true, "which format to output")); options.addOption(new Option("f", "format", true, "which format to output"));
options.addOption(new Option("", "version",true, "which version of the standard to use")); options.addOption(new Option("", "version", true, "which version of the standard to use"));
options.addOption(new Option("", "profile",true, "which profile of the standard to use")); options.addOption(new Option("", "profile", true, "which profile of the standard to use"));
Option attachmentOpt=new Option("", "attachments", true, "File attachments"); Option attachmentOpt = new Option("", "attachments", true, "File attachments");
attachmentOpt.setValueSeparator(','); attachmentOpt.setValueSeparator(',');
attachmentOpt.setArgs(Option.UNLIMITED_VALUES); attachmentOpt.setArgs(Option.UNLIMITED_VALUES);
options.addOption(attachmentOpt); options.addOption(attachmentOpt);
options.addOption(new Option("", "source",true, "which source file to use")); options.addOption(new Option("", "source", true, "which source file to use"));
options.addOption(new Option("", "source-xml",true, "which source file to use")); options.addOption(new Option("", "source-xml", true, "which source file to use"));
options.addOption(new Option("", "language",true, "output language (en, de or fr)")); options.addOption(new Option("", "language", true, "output language (en, de or fr)"));
options.addOption(new Option("", "out",true, "which output file to write to")); options.addOption(new Option("", "out", true, "which output file to write to"));
options.addOption(new Option("", "no-notices",false, "suppress non-fatal errors")); options.addOption(new Option("", "no-notices", false, "suppress non-fatal errors"));
options.addOption(new Option("", "logAppend",true, "freeform text to be appended to log messages")); options.addOption(new Option("", "logAppend", true, "freeform text to be appended to log messages"));
options.addOption(new Option("d", "directory",true, "which directory to operate on")); options.addOption(new Option("d", "directory", true, "which directory to operate on"));
options.addOption(new Option("i", "ignorefileextension",false, "ignore non-matching file extensions")); options.addOption(new Option("i", "ignorefileextension", false, "ignore non-matching file extensions"));
options.addOption(new Option("l", "listfromstdin",false, "take list of files from commandline")); options.addOption(new Option("l", "listfromstdin", false, "take list of files from commandline"));
boolean optionsRecognized=false; boolean optionsRecognized = false;
String action = ""; String action = "";
try { try {
cmd = parser.parse(options, args); cmd = parser.parse(options, args);
@@ -369,7 +370,7 @@ public class Main {
String directoryName = cmd.getOptionValue("directory"); String directoryName = cmd.getOptionValue("directory");
Boolean filesFromStdIn = cmd.hasOption("listfromstdin");//((Number)cmdLine.getParsedOptionValue("integer-option")).intValue(); Boolean filesFromStdIn = cmd.hasOption("listfromstdin");//((Number)cmdLine.getParsedOptionValue("integer-option")).intValue();
Boolean ignoreFileExt = cmd.hasOption("ignorefileextension"); Boolean ignoreFileExt = cmd.hasOption("ignorefileextension");
Boolean helpRequested = cmd.hasOption("help") || ((action!=null)&&(action.equals("help"))); Boolean helpRequested = cmd.hasOption("help") || ((action != null) && (action.equals("help")));
String sourceName = cmd.getOptionValue("source"); String sourceName = cmd.getOptionValue("source");
String sourceXMLName = cmd.getOptionValue("source-xml"); String sourceXMLName = cmd.getOptionValue("source-xml");
@@ -384,49 +385,50 @@ public class Main {
String[] attachmentFilenames = cmd.hasOption("attachments") ? cmd.getOptionValues("attachments") : null; String[] attachmentFilenames = cmd.hasOption("attachments") ? cmd.getOptionValues("attachments") : null;
ArrayList<FileAttachment> attachments = new ArrayList<>();
ArrayList<FileAttachment> attachments=new ArrayList <>();
if (helpRequested) { if (helpRequested) {
printHelp(); printHelp();
optionsRecognized=true; optionsRecognized = true;
} /* else if ((action!=null)&&(action.equals("license"))) { } /* else if ((action!=null)&&(action.equals("license"))) {
printLicense(); printLicense();
optionsRecognized=true; optionsRecognized=true;
} */ else if ((action!=null)&&(action.equals("metrics"))) { } */ else if ((action != null) && (action.equals("metrics"))) {
performMetrics(directoryName, filesFromStdIn, ignoreFileExt); performMetrics(directoryName, filesFromStdIn, ignoreFileExt);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("combine"))) { } else if ((action != null) && (action.equals("combine"))) {
performCombine(sourceName, sourceXMLName, outName, format, zugferdVersion, zugferdProfile, ignoreFileExt, attachmentFilenames, attachments); performCombine(sourceName, sourceXMLName, outName, format, zugferdVersion, zugferdProfile, ignoreFileExt, attachmentFilenames, attachments);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("extract"))) { } else if ((action != null) && (action.equals("extract"))) {
performExtract(sourceName, outName); performExtract(sourceName, outName);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("a3only"))) { } else if ((action != null) && (action.equals("a3only"))) {
performConvert(sourceName, outName); performConvert(sourceName, outName);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("visualize"))) { } else if ((action != null) && (action.equals("pdf"))) {
performVisualization(sourceName, lang, outName); performVisualization(sourceName, lang, outName, true);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("upgrade"))) { } else if ((action != null) && (action.equals("visualize"))) {
performVisualization(sourceName, lang, outName, false);
optionsRecognized = true;
} else if ((action != null) && (action.equals("upgrade"))) {
performUpgrade(sourceName, outName); performUpgrade(sourceName, outName);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("ubl"))) { } else if ((action != null) && (action.equals("ubl"))) {
performUBL(sourceName, outName); performUBL(sourceName, outName);
optionsRecognized=true; optionsRecognized = true;
} else if ((action!=null)&&(action.equals("validate"))) { } else if ((action != null) && (action.equals("validate"))) {
optionsRecognized=performValidate(sourceName, noNotices!=null&&noNotices, cmd.getOptionValue("logAppend")); optionsRecognized = performValidate(sourceName, noNotices != null && noNotices, cmd.getOptionValue("logAppend"));
} else if ((action!=null)&&(action.equals("validateExpectValid"))) { } else if ((action != null) && (action.equals("validateExpectValid"))) {
optionsRecognized=performValidateExpect(true, directoryName); optionsRecognized = performValidateExpect(true, directoryName);
} else if ((action!=null)&&(action.equals("validateExpectInvalid"))) { } else if ((action != null) && (action.equals("validateExpectInvalid"))) {
optionsRecognized=performValidateExpect(false, directoryName); optionsRecognized = performValidateExpect(false, directoryName);
} }
} catch (UnrecognizedOptionException ex) { } catch (UnrecognizedOptionException ex) {
optionsRecognized=false; optionsRecognized = false;
} }
if (!optionsRecognized){ if (!optionsRecognized) {
// no argument or argument unknown // no argument or argument unknown
printUsage(); printUsage();
System.exit(2); System.exit(2);
@@ -443,8 +445,8 @@ public class Main {
if (sourceName == null) { if (sourceName == null) {
sourceName = getFilenameFromUser("Source PDF or XML", "invoice.pdf", "pdf|xml", true, false); sourceName = getFilenameFromUser("Source PDF or XML", "invoice.pdf", "pdf|xml", true, false);
} }
ZUGFeRDValidator zfv=new ZUGFeRDValidator(); ZUGFeRDValidator zfv = new ZUGFeRDValidator();
if ((logAppend!=null)&&(logAppend.length()>0)) { if ((logAppend != null) && (logAppend.length() > 0)) {
zfv.setLogAppend(logAppend); zfv.setLogAppend(logAppend);
} }
if (noNotices) { if (noNotices) {
@@ -468,13 +470,13 @@ public class Main {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e1.printStackTrace(); e1.printStackTrace();
} }
String totalResult="valid"; String totalResult = "valid";
if (!zfWalk.getResult()) { if (!zfWalk.getResult()) {
totalResult="invalid"; totalResult = "invalid";
System.exit(-1); System.exit(-1);
} }
System.out.println("Overall test result: "+totalResult); System.out.println("Overall test result: " + totalResult);
return true; return true;
} }
@@ -539,7 +541,7 @@ public class Main {
} }
private static void performCombine(String pdfName, String xmlName, String outName, String format, String zfVersion, private static void performCombine(String pdfName, String xmlName, String outName, String format, String zfVersion,
String zfProfile, Boolean ignoreInputErrors, String[] attachmentFilenames, ArrayList <FileAttachment> attachments) throws Exception { String zfProfile, Boolean ignoreInputErrors, String[] attachmentFilenames, ArrayList<FileAttachment> attachments) throws Exception {
/* /*
* ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory() * ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory()
* .setProducer("toecount") .setCreator(System.getProperty("user.name")) * .setProducer("toecount") .setCreator(System.getProperty("user.name"))
@@ -568,12 +570,12 @@ public class Main {
} }
if (attachmentFilenames == null) { if (attachmentFilenames == null) {
byte attachmentContents[]=null; byte attachmentContents[] = null;
String attachmentFilename, attachmentMime, attachmentDescription; String attachmentFilename, attachmentMime, attachmentDescription;
attachmentFilename = getFilenameFromUser("Additional file attachments filename (empty for none)", "", "pdf", true, false); attachmentFilename = getFilenameFromUser("Additional file attachments filename (empty for none)", "", "pdf", true, false);
if (attachmentFilename.length()!=0) { if (attachmentFilename.length() != 0) {
attachmentContents=Files.readAllBytes(Paths.get(attachmentFilename)); attachmentContents = Files.readAllBytes(Paths.get(attachmentFilename));
attachmentMime= Files.probeContentType(Paths.get(attachmentFilename)); attachmentMime = Files.probeContentType(Paths.get(attachmentFilename));
attachments.add(new FileAttachment(attachmentFilename, attachmentMime, "Data", attachmentContents)); attachments.add(new FileAttachment(attachmentFilename, attachmentMime, "Data", attachmentContents));
} }
} else { } else {
@@ -611,9 +613,9 @@ public class Main {
if (zfProfile == null) { if (zfProfile == null) {
try { try {
if ((format.equals("zf") && (zfIntVersion == 1)) || (format.equals("ox") )) { if ((format.equals("zf") && (zfIntVersion == 1)) || (format.equals("ox"))) {
zfProfile = getStringFromUser("Profile (b)asic, (c)omfort or ex(t)ended", "t", "B|b|C|c|T|t"); zfProfile = getStringFromUser("Profile (b)asic, (c)omfort or ex(t)ended", "t", "B|b|C|c|T|t");
} else if ( (format.equals("da"))) { } else if ((format.equals("da"))) {
zfProfile = getStringFromUser("Profile (p)ilot", "p", "P|p"); zfProfile = getStringFromUser("Profile (p)ilot", "p", "P|p");
} else { } else {
zfProfile = getStringFromUser( zfProfile = getStringFromUser(
@@ -629,7 +631,6 @@ public class Main {
zfProfile = zfProfile.toLowerCase(); zfProfile = zfProfile.toLowerCase();
// Verify params // Verify params
ensureFileExists(pdfName); ensureFileExists(pdfName);
ensureFileExists(xmlName); ensureFileExists(xmlName);
@@ -639,18 +640,17 @@ public class Main {
throw new Exception("Factur-X is only available in version 1 (roughly corresponding to ZF2)"); throw new Exception("Factur-X is only available in version 1 (roughly corresponding to ZF2)");
} }
EStandard standard=EStandard.facturx; EStandard standard = EStandard.facturx;
if (format.equals("zf")) { if (format.equals("zf")) {
standard=EStandard.zugferd; standard = EStandard.zugferd;
} }
if (format.equals("da")) { if (format.equals("da")) {
standard=EStandard.despatchadvice; standard = EStandard.despatchadvice;
zfConformanceLevelProfile = Profiles.getByName(standard, "PILOT", 1); zfConformanceLevelProfile = Profiles.getByName(standard, "PILOT", 1);
} } else if (((format.equals("zf")) && (zfIntVersion == 1)) || (format.equals("ox"))) {
else if (((format.equals("zf")) && (zfIntVersion == 1))||(format.equals("ox"))) {
if (format.equals("ox")) { if (format.equals("ox")) {
standard=EStandard.orderx; standard = EStandard.orderx;
} }
if (zfProfile.equals("b")) { if (zfProfile.equals("b")) {
zfConformanceLevelProfile = Profiles.getByName(standard, "BASIC", zfIntVersion); zfConformanceLevelProfile = Profiles.getByName(standard, "BASIC", zfIntVersion);
@@ -683,14 +683,14 @@ public class Main {
throw new Exception(String.format("Unknown version '%i'", zfIntVersion)); throw new Exception(String.format("Unknown version '%i'", zfIntVersion));
} }
IZUGFeRDExporter ze=null; IZUGFeRDExporter ze = null;
// All params are good! continue... // All params are good! continue...
if (format.equals("ox")) { if (format.equals("ox")) {
ze = new OXExporterFromA1().setProducer("Mustang-cli") ze = new OXExporterFromA1().setProducer("Mustang-cli")
.setZUGFeRDVersion(zfIntVersion) .setZUGFeRDVersion(zfIntVersion)
.setCreator(System.getProperty("user.name")).setProfile(zfConformanceLevelProfile); .setCreator(System.getProperty("user.name")).setProfile(zfConformanceLevelProfile);
if (ignoreInputErrors) { if (ignoreInputErrors) {
((OXExporterFromA1)ze).ignorePDFAErrors(); ((OXExporterFromA1) ze).ignorePDFAErrors();
} }
} else if (format.equals("da")) { } else if (format.equals("da")) {
@@ -699,7 +699,7 @@ public class Main {
.setCreator(System.getProperty("user.name")).setProfile(zfConformanceLevelProfile); .setCreator(System.getProperty("user.name")).setProfile(zfConformanceLevelProfile);
if (ignoreInputErrors) { if (ignoreInputErrors) {
((DXExporterFromA1)ze).ignorePDFAErrors(); ((DXExporterFromA1) ze).ignorePDFAErrors();
} }
} else { } else {
@@ -707,10 +707,10 @@ public class Main {
.setZUGFeRDVersion(standard, zfIntVersion) .setZUGFeRDVersion(standard, zfIntVersion)
.setCreator(System.getProperty("user.name")).setProfile(zfConformanceLevelProfile); .setCreator(System.getProperty("user.name")).setProfile(zfConformanceLevelProfile);
if (ignoreInputErrors) { if (ignoreInputErrors) {
((ZUGFeRDExporterFromA1)ze).ignorePDFAErrors(); ((ZUGFeRDExporterFromA1) ze).ignorePDFAErrors();
} }
} }
for (FileAttachment attachment: attachments) { for (FileAttachment attachment : attachments) {
((ZUGFeRDExporterFromA3) ze).attachFile(attachment.getFilename(), attachment.getData(), attachment.getMimetype(), attachment.getRelation()); ((ZUGFeRDExporterFromA3) ze).attachFile(attachment.getFilename(), attachment.getData(), attachment.getMimetype(), attachment.getRelation());
} }
@@ -769,27 +769,35 @@ public class Main {
System.out.println(sr.getSummaryLine()); System.out.println(sr.getSummaryLine());
} }
private static void performVisualization(String sourceName, String lang, String outName) { private static void performVisualization(String sourceName, String lang, String outName, boolean intoPDF) {
// Get params from user if not already defined // Get params from user if not already defined
if (sourceName == null) { if (sourceName == null) {
sourceName = getFilenameFromUser("ZUGFeRD XML source", "factur-x.xml", "xml", true, false); sourceName = getFilenameFromUser("ZUGFeRD XML source", "factur-x.xml", "xml", true, false);
} else { } else {
System.out.println("ZUGFeRD XML source set to " + sourceName); System.out.println("ZUGFeRD XML source set to " + sourceName);
} }
if (!intoPDF) {
if (lang == null) { if (lang == null) {
try { try {
lang = getStringFromUser("Output language", "en", "en|de|fr"); lang = getStringFromUser("Output language", "en", "en|de|fr");
} catch(Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage(), e); LOGGER.error(e.getMessage(), e);
} }
} else { } else {
System.out.println("Output language set to " + lang); System.out.println("Output language set to " + lang);
} }
}
if (outName == null) { if (outName == null) {
outName = getFilenameFromUser("HTML target file", "factur-x.html", "html", false, true); String defaultFilename = "factur-x.html";
String defaultExtension = "html";
if (intoPDF) {
defaultFilename = "factur-x.pdf";
defaultExtension = "pdf";
}
outName = getFilenameFromUser("Target file", defaultFilename, defaultExtension, false, true);
} else { } else {
System.out.println("HTML target set to " + outName); System.out.println("Target set to " + outName);
} }
// Verify params // Verify params
@@ -805,15 +813,19 @@ public class Main {
ZUGFeRDVisualizer zvi = new ZUGFeRDVisualizer(); ZUGFeRDVisualizer zvi = new ZUGFeRDVisualizer();
String xml = null; String xml = null;
try { try {
ZUGFeRDVisualizer.Language langCode=ZUGFeRDVisualizer.Language.EN; if (!intoPDF) {
ZUGFeRDVisualizer.Language langCode = ZUGFeRDVisualizer.Language.EN;
if (lang.equalsIgnoreCase("de")) { if (lang.equalsIgnoreCase("de")) {
langCode=ZUGFeRDVisualizer.Language.DE; langCode = ZUGFeRDVisualizer.Language.DE;
} }
if (lang.equalsIgnoreCase("fr")) { if (lang.equalsIgnoreCase("fr")) {
langCode=ZUGFeRDVisualizer.Language.FR; langCode = ZUGFeRDVisualizer.Language.FR;
} }
xml = zvi.visualize(sourceName, langCode); xml = zvi.visualize(sourceName, langCode);
Files.write(Paths.get(outName), xml.getBytes()); Files.write(Paths.get(outName), xml.getBytes());
} else {
zvi.toPDF(sourceName, outName);
}
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
LOGGER.error(e.getMessage(), e); LOGGER.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
@@ -825,6 +837,8 @@ public class Main {
} }
System.out.println("Written to " + outName); System.out.println("Written to " + outName);
if (!intoPDF) {
try { try {
ExportResource("/xrechnung-viewer.css"); ExportResource("/xrechnung-viewer.css");
ExportResource("/xrechnung-viewer.js"); ExportResource("/xrechnung-viewer.js");
@@ -833,6 +847,7 @@ public class Main {
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage(), e); LOGGER.error(e.getMessage(), e);
} }
}
} }
@@ -850,7 +865,7 @@ public class Main {
String jarFolder; String jarFolder;
try { try {
stream = Main.class.getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree stream = Main.class.getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree
if(stream == null) { if (stream == null) {
throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file."); throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file.");
} }