package demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class DocxToPdf {
public static void main(String[] args){
try
{
String inputFile = "F:\\MY WORK\\CollectionPractice\\WebContent\\APCR1.docx";
String outputFile = "F:\\MY WORK\\CollectionPractice\\WebContent\\APCR1.pdf";
System.out.println("inputFile:" + inputFile + ",outputFile:" + outputFile);
FileInputStream in = new FileInputStream(inputFile);
XWPFDocument document = new XWPFDocument(in);
File outFile = new File(outputFile);
OutputStream out = new FileOutputStream(outFile);
PdfOptions options = null;
PdfConverter.getInstance().convert(document, out, options);
} catch (Exception e) {
e.printStackTrace();
}
}
}
when i run this code an error occur like these and i have used following jar files also.
error:
java.lang.NoSuchMethodError: org.apache.poi.POIXMLDocumentPart.getPackageRelationship()Lorg/apache/poi/openxml4j/opc/PackageRelationship;
jars:
List of jar files
You likely have jar-versions of POI mixed up. The error indicates that the class that was loaded did not have a method that the calling class saw during compilation, so you have a different version of POI in your classpath.
See "Component Map" at https://poi.apache.org/overview.html for the different components that are included and which jars they end up, make sure you only have one of these jars in your classpath, not multiple different versions.
Related
I am trying to convert a docx file into pdf file using POI. Getting following error.
Using poi-3.17 ,
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class WordToPDF {
public static void main(String[] args) {
WordToPDF cwoWord = new WordToPDF();
System.out.println("Start");
cwoWord.ConvertToPDF("D:\\2067536.docx", "D:\\2067536.pdf");
}
public void ConvertToPDF(String docPath, String pdfPath) {
try {
InputStream doc = new FileInputStream(new File(docPath));
XWPFDocument document = new XWPFDocument(doc);
document.createStyles();
PdfOptions options = PdfOptions.create();
OutputStream out = new FileOutputStream(new File(pdfPath));
PdfConverter.getInstance().convert(document, out, options);
System.out.println("Done");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Here is the Error happening
Exception in thread "main" org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.NullPointerException
at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:70)
at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:38)
at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
at WordToPDF.ConvertToPDF(WordToPDF.java:27)
at WordToPDF.main(WordToPDF.java:17)
Caused by: java.lang.NullPointerException
at org.apache.poi.xwpf.converter.pdf.internal.PdfMapper.visitHeader(PdfMapper.java:178)
at org.apache.poi.xwpf.converter.pdf.internal.PdfMapper.visitHeader(PdfMapper.java:111)
at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.visitHeaderRef(XWPFDocumentVisitor.java:1142)
at org.apache.poi.xwpf.converter.core.MasterPageManager.visitHeadersFooters(MasterPageManager.java:213)
at org.apache.poi.xwpf.converter.core.MasterPageManager.addSection(MasterPageManager.java:180)
at org.apache.poi.xwpf.converter.core.MasterPageManager.compute(MasterPageManager.java:127)
at org.apache.poi.xwpf.converter.core.MasterPageManager.initialize(MasterPageManager.java:90)
at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.visitBodyElements(XWPFDocumentVisitor.java:232)
at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.start(XWPFDocumentVisitor.java:199)
at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:56)
... 4 more
As this is a null pointer error I am unable to understand what exactly the issue might be, any help is appreciated. Thank you.
Libre Office Saved my life, Simple one liner command for docx to pdf conversion works like a charm.
Detailed answer here
Command `libreoffice --headless --convert-to pdf test.docx --outdir /pdf` is not working
Consider a simple Java file which creates a BufferedInputStream to copy a local file 1400-8.txt to Hadoop HDFS and print some dots as a progress status. The example is Example 3-3 from the Hadoop book here.
// cc FileCopyWithProgress Copies a local file to a Hadoop filesystem, and shows progress
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;
// vv FileCopyWithProgress
public class FileCopyWithProgress {
public static void main(String[] args) throws Exception {
String localSrc = args[0];
String dst = args[1];
InputStream in = new BufferedInputStream(new FileInputStream(localSrc));
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(dst), conf);
OutputStream out = fs.create(new Path(dst), new Progressable() {
public void progress() {
System.out.print(".");
}
});
IOUtils.copyBytes(in, out, 4096, true);
}
}
// ^^ FileCopyWithProgress
I compile the code and create the JAR file with
hadoop com.sun.tools.javac.Main FileCopyWithProgress.java
jar cf FileCopyWithProgress.jar FileCopyWithProgress.class
The above commands generate the files FileCopyWithProgress.class, FileCopyWithProgress$1.class and FileCopyWithProgress.jar. Then, I try to run it
hadoop jar FileCopyWithProgress.jar FileCopyWithProgress 1400-8.txt hdfs://localhost:9000/user/kostas/1400-8.txt
But, I receive the error
Exception in thread "main" java.lang.NoClassDefFoundError:
FileCopyWithProgress$1
To my understanding, the FileCopyWithProgress$1.class is due to the anonymous callback function the program declares. But since the file exists what is the issue here? Am I running the correct sequence of commands?
I found the issue so I am just posting in case it helps someone. I had to include the class FileCopyWithProgress$1.class in the JAR. The correct one should be
jar cf FileCopyWithProgress.jar FileCopyWithProgress*.class
I need to generate SVG from given DXF file. I try to archive that by using kabeja package. This is the code that they gave on their web page.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xml.sax.ContentHandler;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.DXFParseException;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.SAXGenerator;
public class MyClass{
public MyClass(){
...
}
public void parseFile(String sourceFile) {
Parser parser = ParserBuilder.createDefaultParser();
try {
parser.parse(new FileInputStream(sourceFile));
DXFDocument doc = parser.getDocument();
//the SVG will be emitted as SAX-Events
//see org.xml.sax.ContentHandler for more information
ContentHandler myhandler = new ContentHandlerImpl();
//the output - create first a SAXGenerator (SVG here)
SAXGenerator generator = new SVGGenerator();
//setup properties
generator.setProperties(new HashMap());
//start the output
generator.generate(doc,myhandler);
} catch (DXFParseException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Hear is the code that provided by the kabeja development group on sourceforge web site. But in above code I noticed that some of the classes are missing on their new package. for example
ContentHandler myhandler = new ContentHandlerImpl();
In this line it create contentHandlerImpl object but with new kabeja package it dosn't have that class.So because of this it doesn't generate SVG file. So could some one explain me how to archive my target by using this package.
Try to read symbol ContentHandlerImpl not found from kabeja's forum
I am writing an updater. I have this code:
package main;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.Pattern;
import java.lang.*;
import static java.lang.System.out;
public class UpdaterCore
{
public static void main(String args[]) throws IOException
{
java.io.BufferedInputStream inv = new java.io.BufferedInputStream(new
java.net.URL("http://unicombox.tk/update/nv").openStream());
java.io.FileOutputStream fosv = new java.io.FileOutputStream("nv");
java.io.BufferedOutputStream boutv = new BufferedOutputStream(fosv,1024);
byte data[] = new byte[1024];
while(inv.read(data,0,1024)>=0)
{
boutv.write(data);
}
boutv.close();
inv.close();
//end version download
Scanner VersionReader= new Scanner(new File ("v")).useDelimiter(",");
int currentVersion= VersionReader.nextInt();
VersionReader.close();
Scanner NewVersionReader= new Scanner(new File ("nv")).useDelimiter(",");
int newVersion= NewVersionReader.nextInt();
NewVersionReader.close();
if (newVersion>currentVersion){
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL("http://unicombox.tk/update/update.zip").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("update.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data1[] = new byte[1024];
while(in.read(data1,0,1024)>=0)
{
bout.write(data1);
}
bout.close();
in.close();
out.println("Update successfully downloaded!");
}
else{
out.println("You have the latest version!");
}
}
}
It gets the new version from a server, and then compares it to its current version. If the new version is greater than the current version, it downloads the update.
I am having one big problem. My program can never find the files "v" and "nv"!
"v" and "nv" are in the same folder as the compiled jar, yet I get a FileNotFound.
What am I doing wrong?
Get path to current directory (directory where the .jar file is placed) like this:
// import java.io.*;
// import java.net.URLDecoder;
// throws java.io.UnsupportedEncodingException
String path = UpdaterCore.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
System.out.println(decodedPath);
and then create File instance like this
new File (decodedPath + File.separatorChar + "v")
You are probably running the program from a different directory, one level up?
You can use getAbsolutePath() on those java.io.File-s to find out what file path are you really trying to read from.
Or just use Marek Sebera's solution, it is fine.
Hello friends I try to use fop engine programatically I search for an example and I find this class
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;
import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
public class Invokefop
{
public void convertXML2PDF(File xml, File xslt, File pdf)
throws IOException, FOPException, TransformerException {
Driver driver = new Driver();
Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
driver.setLogger(logger);
MessageHandler.setScreenLogger(logger);
driver.setRenderer(Driver.RENDER_PDF);
OutputStream out = new java.io.FileOutputStream(pdf);
try {
driver.setOutputStream(out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(xslt));
Source src = new StreamSource(xml);
Result res = new SAXResult(driver.getContentHandler());
transformer.transform(src, res);
} finally {
out.close();
}
}
public static void main(String[] args) {
try {
System.out.println("JAVA XML2PDF:: FOP ExampleXML2PDF\n");
System.out.println("JAVA XML2PDF:: Preparing...");
File base = new File("../");
File baseDir = new File(base, "in");
File outDir = new File(base, "out");
outDir.mkdirs();
File xmlfile = new File(baseDir, args[0]);
File xsltfile = new File(baseDir, args[1]);
File pdffile = new File(outDir, args[2]);
System.out.println("JAVA XML2PDF:: Input: XML (" + xmlfile + ")");
System.out.println("JAVA XML2PDF:: Stylesheet: " + xsltfile);
System.out.println("JAVA XML2PDF:: Output: PDF (" + pdffile + ")");
System.out.println();
System.out.println("JAVA XML2PDF:: Transforming...");
Invokefop app = new Invokefop();
app.convertXML2PDF(xmlfile, xsltfile, pdffile);
System.out.println("JAVA XML2PDF:: Success!");
} catch (Exception e) {
System.err.println(ExceptionUtil.printStackTrace(e));
System.exit(-1);
}
}
}
All the Libs from Fop are in the Classpath including the fop.jar in build directory. After
I run thejavac Invokefop.java I get this error:
> C:\....\fop>javac Invokefop.java
Invokefop.java:21: cannot find symbol
symbol : class Driver
location: package org.apache.fop.apps
import org.apache.fop.apps.Driver;
^
Invokefop.java:23: package org.apache.fop.messaging does not exist
import org.apache.fop.messaging.MessageHandler;
^
Invokefop.java:31: cannot find symbol
symbol : class Driver
location: class Invokefop
Driver driver = new Driver();
^
Invokefop.java:31: cannot find symbol
symbol : class Driver
location: class Invokefop
Driver driver = new Driver();
^
Invokefop.java:36: cannot find symbol
symbol : variable MessageHandler
location: class Invokefop
MessageHandler.setScreenLogger(logger);
^
Invokefop.java:39: cannot find symbol
symbol : variable Driver
location: class Invokefop
driver.setRenderer(Driver.RENDER_PDF);
^
6 errors
I am relatively new to Java, but with this approach I try to execute the fop engine in c++ using this java class..
Have anybody some Idea, how to solve this errors...
Thanx in advance..
The classes that are coming up with "cannot find symbol" errors don't exist in the fop.jar file.
I just downloaded v0.95 of the FOP library, and I can't see those classes in any of the jar files in the distribution. (You can open a jar file in any zip program and have a look - a jar is basically a zip file with a few extra bits in there that Java uses).
I would guess that the classes referenced in your example code were removed at some stage from the FOP library, and the example is for the older version. So you could try and find an older version of the library that contains those classes, or look for newer examples. The binary distribution comes with some examples - maybe have a look through those to see if any are useful for you?
In my case I added the dependency in pom.xml
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>2.5</version>
</dependency>