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