Did Matlab 2017a change how it imports external java classes? - java

I'm calling PDFBox from Matlab to figure out how many pages there are in a PDF. Everything works great with Matlba 2016b and prior. I can import the library and load a PDF without a problem:
import org.apache.pdfbox.pdmodel.PDDocument;
pdfFile = PDDocument.load(filename);
When I run the same thing in 2017a, I get the following error:
No method 'load' with matching signature found for class
'org.apache.pdfbox.pdmodel.PDDocument'.
I can change the line after the import so that the function signature matches:
jFilename = java.lang.String(filename);
pdfFile = PDDocument.load(jFilename.getBytes());
However, this causes PDFBox to have problems when I call load:
Java exception occurred:
java.io.IOException: Error: End-of-File, expected line
at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1111)
at org.apache.pdfbox.pdfparser.COSParser.parseHeader(COSParser.java:1874)
at org.apache.pdfbox.pdfparser.COSParser.parsePDFHeader(COSParser.java:1853)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:242)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1093)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1071)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1053)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1038)
This error seems to occur regardless of the PDF I'm trying to load. I'm getting the same exception with PDFBox 1.8.10 and 2.0.6.
I'm left with 2 questions:
Did Matlab 2017a change how it passes strings to Java? I didn't see anything in the release notes about this.
What could be causing the PDFBox error? Matlab is still on Java 1.7 in 2017a so I wouldn't think there should be any difference in how PDFBox works.

It seems like the method you are calling is from PDDocument version 1.8.11
In the latest version, PDDocument version 2.0.2 the method signature for accepting a file name no longer exists.
Change your code to the following, and it should work.
pdfFile = PDDocument.load(java.io.File(filename));

Related

Standard Method TEXT is undefined when compiling jasper report

When I package my stand-alone-java-application, that compiles, renders and prints Jasper-Reports, in a fat jar with all dependencies, I get the error that the function TEXT – a function used in the report and defined in the net.sf.jasperreports-functions-library is not found.
The method TEXT(Integer, String) is undefined for the type [...]
value = IF(LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#"))==2,"***",REPT("*",6-LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#")))) //$JR_EXPR_ID=58$
Other functions from the same library work. When I run the application with gradle run, the function is found and the report can be printed. The library is on my classpath.
There are several similar questions on this site and Stackoverflow, but neither provided answers, that worked for me. In the following, I will explain what I tried:
In my build.gradle-File I defined dependencies to the following libraries:
implementation('net.sf.jasperreports:jasperreports:6.18.1')
implementation('net.sf.jasperreports:jasperreports-functions:6.18.1')
In my java-Files, I created a DesignFile and statically imported the functions into it. I tried two methods:
Method 1 as given in an answer in this thread: Unresolved symbols when compiling jasper report
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());
designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.MathFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.DateTimeFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.LogicalFunctions.*");
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/
Method 2: importing each function on its own
public static String[] textFunctions(){
return new String[]{"BASE", "CHAR", "CLEAN", "CODE", "CONCATENATE", "DOUBLE_VALUE",
"EXACT", "FIND", /*"FIXED", */"FLOAT_VALUE", "INTEGER_VALUE", "LEFT", "LEN", "LONG_VALUE",
"LOWER", "LTRIM", "MID", "PROPER", "REPLACE", "REPT", "RIGHT", "RTRIM", "SEARCH", "SUBSTITUTE",
"T", /*"TEXT",*/ "TRIM", "UPPER"};
}}
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());
for (String textFunction : textFunctions()){
designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions." + textFunction);
}/* similarly for logical functions, numeric functions and datetime functions*/
}
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/
As you can see, the function TEXT is commented out. That’s because the program fails at runtime when run with “gradle run”, when I comment it in:
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. The import net.sf.jasperreports.functions.standard.TextFunctions.TEXT cannot be resolved
import static net.sf.jasperreports.functions.standard.TextFunctions.TEXT;
The same thing is true with most datetime-functions, in fact, only TIME can be imported to the DesignObject without error at runtime
In addition to that, when I type net.sf.jasperreports.functions.standard.TextFunctions. in my IDE, the content-assist shows a list of available functions, yet TEXT is missing.
I suspected, that the function is simply missing in the library, but it is there. In the .gradle/cache/modules-2/files-2.1/… directory, there is the jar with the TextFunctions.java, that contains the function TEXT:
When building the FatJar with dependencies, I have a TextFunctions.class-File in it, that contains the TEXT-Function as well.
In my jar, there are two jasperreports_extension.properties on the root level:
with the smaller one (from the jasperreport-functions-dependency) containing the following lines:
net.sf.jasperreports.extension.registry.factory.functions=net.sf.jasperreports.functions.FunctionsRegistryFactory
net.sf.jasperreports.extension.functions.datetime=net.sf.jasperreports.functions.standard.DateTimeFunctions
net.sf.jasperreports.extension.functions.math=net.sf.jasperreports.functions.standard.MathFunctions, net.sf.jasperreports.functions.standard.LogicalFunctions
net.sf.jasperreports.extension.functions.text=net.sf.jasperreports.functions.standard.TextFunctions
net.sf.jasperreports.extension.functions.report=net.sf.jasperreports.functions.standard.ReportFunctions
Funnily enough, commenting out TEXT, running it locally with gradle run, it works without problems. But packaging it and running it with java -jar it fails to find this function. And statically importing this function leads to gradle run failing as well.
What is happening and how can I fix this? I want to distribute my FatJar on a server and run it, but this problems makes it impossible for me.

Convert XPS-File to Text with Java

I wish to convert a .XPS File to Text with Java or Kotlin.
Aspose is to expensive for me.
I found Java-AXP, which should do the job but I did not find any documentation or sample code for it.
I managed to get the Java-AXP Core to my project libraries in IntelliJ. I can now access the files from within my project. But actually understanding how to use the library to get the text converstion is way beyond me.
The only attempt to use the library with example code I found here:
File b =new File("D:\\Chemia\\Clients\\Clients\\Docs\\Equipment\\CCP\\XPSOCRDemo.xps");
IXPSAccess access = new XPSFileAccessImpl(b);
IXPSFileAccess xpsFileAccess = access.getFileAccess();
XPSDocumentAccessImpl xpsimpl=new XPSDocumentAccessImpl(access);
int docunum = xpsimpl.getFirstDocNum();
IDocumentStructure structure=xpsimpl.getDocumentStructure(docunum);
List<IOutlineEntry> list=(List<IOutlineEntry>)
structure.getDocumentStructureOutline().getDocumentOutline().getOutlineEntry(
);
list.stream().forEach(restu->{
System.out.println( restu.getOutlineTarget());
});
However, I do get the same null pointer exeption as the OP and I can't fix it. I'd need a working example code to continue on my own.
So how can I use Java-AXP? Or are there alternative libraries? I am open to use anything.
Thanks for any help.
Edit:
#Abra Thanks.
Exception in thread "main" java.lang.IllegalStateException: structure must not be null
at MainKt.main(main.kt:80)
at MainKt.main(main.kt)
73 | val structure = xpsimpl.getDocumentStructure(0)
80 | val list = structure.documentStructureOutline?.documentOutline?.outlineEntry as List<IOutlineEntry>?
xpsimpl.getDocumentStructure(docunum) is null
I can not use a website for my purpose because the XPS files contain sensitive information.
Edit: Here is the solution I found.
I found this repo which uses Java-AXP. However there seemed to be some differences to the java-axp-core.jar I used from
Google Code
So I copied the javaaxp folder to my project.
It needed Apache Tika so I downloaded tika-app-2.1.0.jar from Apache Tika and included it in my project via the Project Structure menu.
In XPSZipFileAccess.java I had a wrong import for IOUtils so I changed
import org.apache.tika.io.IOUtils;
to
import org.apache.commons.io.IOUtils;
Now the Java-AXP could resolve all references.
Then I copied XPSParser.java to the root of my project and made sure all imports work.
In DocSaver.java on line 90 I found where XPSParser was used and I adapted the code so I could convert the XPS file to text:
val xpsFile = File(path + "filename.xps")
val inputStream = FileInputStream(xpsFile)
val metadata = Metadata()
val handler = BodyContentHandler()
XPSParser().parse(inputStream, handler, metadata, ParseContext())
val docContents = handler.toString()
println(docContents)
inputStream.close()
Hope it helps someone.
Here is the solution I found.
I found this repo which uses Java-AXP. However there seemed to be some differences to the java-axp-core.jar I used from
Google Code
So I copied the javaaxp folder to my project.
It needed Apache Tika so I downloaded tika-app-2.1.0.jar from Apache Tika and included it in my project via the Project Structure menu.
In XPSZipFileAccess.java I had a wrong import for IOUtils so I changed
import org.apache.tika.io.IOUtils;
to
import org.apache.commons.io.IOUtils;
Now the Java-AXP could resolve all references.
Then I copied XPSParser.java to the root of my project and made sure all imports work.
In DocSaver.java on line 90 I found where XPSParser was used and I adapted the code so I could convert the XPS file to text:
val xpsFile = File(path + "filename.xps")
val inputStream = FileInputStream(xpsFile)
val metadata = Metadata()
val handler = BodyContentHandler()
XPSParser().parse(inputStream, handler, metadata, ParseContext())
val docContents = handler.toString()
println(docContents)
inputStream.close()

Exception in thread "main" java.lang.RuntimeException: Not yet implemented

I am fetching some problem when I trying to print Arabic letter by using DirectPrint bean. This is a pjc. English fonts are printed fine, but when I want to print Arabic there is showing a exception below:
Exception in thread "main" java.lang.RuntimeException: Not yet implemented
at org.pdfbox.pdmodel.font.PDType0Font.drawString(PDType0Font.java:75)
at org.pdfbox.pdfviewer.PageDrawer.showCharacter(PageDrawer.java:160)
at org.pdfbox.util.PDFStreamEngine.showString(PDFStreamEngine.java:409)
at org.pdfbox.util.operator.ShowTextGlyph.process(ShowTextGlyph.java:80)
at org.pdfbox.util.PDFStreamEngine.processOperator(PDFStreamEngine.java:452)
at org.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:215)
at org.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:174)
at org.pdfbox.pdfviewer.PageDrawer.drawPage(PageDrawer.java:104)
at org.pdfbox.pdmodel.PDPage.print(PDPage.java:741)
at sun.print.RasterPrinterJob.printPage(RasterPrinterJob.java:1936)
at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1431)
at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1247)
at dsd.printing.DirectPrint.main(DirectPrint.java:842)
Please help to solve this issue.
Seems like the Arabic characters are not implemented to be converted by the pdfbox library you're using.
What version of PDFBox you are using? What I see from here:
Exception in thread "main" java.lang.RuntimeException: Not yet implemented
at org.pdfbox.pdmodel.font.PDType0Font.drawString(PDType0Font.java:75)
That it says PDType0Font class and drawString method straightly throws 'Not yet implemented' exception but i.e. if I check one of the latest version (i.e. 1.8.10) I can see the method implemented: here
If I would be I would try to change the version of pdfbox library and try again.
EDIT: Thanks to Tilman, latest version info from his comment: 2.0 has been released friday, it should be available for maven: mvnrepository.com/artifact/org.apache.pdfbox/pdfbox

synonyms() error in wordnet

I want to use synonyms () described in 'Intro to the tm package' for R. It uses the wordnet package. The wordnet package downloaded from CRAN does not have Dict (dictionary) in its directory. I downloaded it from the Princeton site and copied it over to the directory. After using sys.setenv() and setDict() for setting paths, I still get this error:
Error in sort(unique(unlist(lapply(synsets, getWord))))
error in evaluating the argument 'x' in selecting a method for function 'sort': Error in unique(unlist(lapply(synsets, getWord))) :
error in evaluating the argument 'x' in selecting a method for function 'unique': Error in .jcall(synset, "Ljava/util/List;", "getWord") :
java.lang.NumberFormatException: For input string: "t"
when I try synonyms("company", pos = "NOUN") or another English word in place of 'company'. The problem is in getSynonyms() called from synonyms(). Any idea on how to fix this problem?
Different combinations lead to different input string NumberFormatException. My Java is version 1.8. I tried all the online resources. I added two paths to PATH for R's bin and RJava's jri. Discussion on the exception indicates it is a string to numeric conversion issue. I have made sure that Java to R linkage (via rJava) works (URL: https://www.rforge.net/rJava/ ).

No Such method error during transformation to pdf in Java

I have a problem while transforming the xslt to pdf in java, i am following the same process posted in this link
"Java Transformation to PDF".
Error:
`
Caused by: java.lang.NoSuchMethodError: org.apache.xmlgraphics.java2d.GraphicContext.<init>(Lorg/apache/xmlgraphics/java2d/GraphicContext;)V
at org.apache.fop.render.intermediate.IFGraphicContext.<init>(IFGraphicContext.java:50)
at org.apache.fop.render.intermediate.IFGraphicContext.clone(IFGraphicContext.java:56)
at org.apache.fop.render.intermediate.IFRenderer.saveGraphicsState(IFRenderer.java:632)
at org.apache.fop.render.intermediate.IFRenderer.startViewport(IFRenderer.java:885)
at org.apache.fop.render.intermediate.IFRenderer.startVParea(IFRenderer.java:878)
at org.apache.fop.render.AbstractRenderer.renderRegionViewport(AbstractRenderer.java:289)
at org.apache.fop.render.intermediate.IFRenderer.renderRegionViewport(IFRenderer.java:731)
at org.apache.fop.render.AbstractRenderer.renderPageAreas(AbstractRenderer.java:249)
at org.apache.fop.render.AbstractRenderer.renderPage(AbstractRenderer.java:230)
at org.apache.fop.render.intermediate.IFRenderer.renderPage(IFRenderer.java:580)
at org.apache.fop.area.RenderPagesModel.addPage(RenderPagesModel.java:114)
at org.apache.fop.layoutmgr.AbstractPageSequenceLayoutManager.finishPage(AbstractPageSequenceLayoutManager.java:312)
at org.apache.fop.layoutmgr.PageSequenceLayoutManager.finishPage(PageSequenceLayoutManager.java:167)
at org.apache.fop.layoutmgr.PageSequenceLayoutManager.activateLayout(PageSequenceLayoutManager.java:109)
at org.apache.fop.area.AreaTreeHandler.endPageSequence(AreaTreeHandler.java:238)
at org.apache.fop.fo.pagination.PageSequence.endOfNode(PageSequence.java:120)
at org.apache.fop.fo.FOTreeBuilder$MainFOHandler.endElement(FOTreeBuilder.java:349)
at org.apache.fop.fo.FOTreeBuilder.endElement(FOTreeBuilder.java:177)
at net.sf.saxon.event.ContentHandlerProxy.endElement(ContentHandlerProxy.java:391)
at net.sf.saxon.event.ProxyReceiver.endElement(ProxyReceiver.java:174)
at net.sf.saxon.event.NamespaceReducer.endElement(NamespaceReducer.java:213)
at net.sf.saxon.event.ComplexContentOutputter.endElement(ComplexContentOutputter.java:417)
at net.sf.saxon.instruct.ElementCreator.processLeavingTail(ElementCreator.java:301)
at net.sf.saxon.instruct.Block.processLeavingTail(Block.java:409)
at net.sf.saxon.instruct.Instruction.process(Instruction.java:94)
at net.sf.saxon.instruct.ElementCreator.processLeavingTail(ElementCreator.java:298)
at net.sf.saxon.instruct.Template.applyLeavingTail(Template.java:175)
at net.sf.saxon.instruct.ApplyTemplates.applyTemplates(ApplyTemplates.java:343)
at net.sf.saxon.Controller.transformDocument(Controller.java:1736)
at net.sf.saxon.Controller.transform(Controller.java:1560)
at mypackage.v2.business.pdf.XMLtoPDF.convertXMLPDF(XMLtoPDF.java:103)
... 51 more
java.lang.ClassCastException: java.lang.NoSuchMethodError cannot be cast to java.lang.Exception
`
Please let me know what could be the problem.
As described in the documentation
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Here's how this can happen. Imagine you built some code that used a library with a method called foo(). You compiled your project and then later decided to upgrade the library. You do this by overwriting the old jar file with the new one. You don't recompile your code.
But what you didn't know is the new library removed the foo() method. Now if you run your code, it will throw this exception because your compile code calls this method and it's no longer there.
In your specific case, this isn't necessarily your code with the problem. It could be that you have one library that uses another library and the problem is there (for example, Library X uses version 2 of Library Y, but you only have Library Y version 1 in your classpath). If this is happening, you need to make sure the libraries are using the version they expect.
For your specific problem, you need to find the version of the jar that has org.apache.xmlgraphics.java2d.GraphicContext in it and it needs to have a constructor that takes a... list of org/apache/xmlgraphics/java2d/GraphicContext... maybe. I forget what (L...;)V means.

Categories

Resources