mohamed.bc
mohamed.bc

Reputation: 57

How to convert .docx file to .pdf in Java

I'm looking for the best way to convert docx file to pdf in Java, this is what I've tried:

File wordFile = new File("wordFile.docx"), target = new File("target.pdf");
IConverter converter;
Future<Boolean> conversion = converter.convert(wordFile)
.as(DocumentType.MS_WORD)
.to(target)
.as(DocumentType.PDF)
.prioritizeWith(1000) // optional
.schedule();

The problem is that I cannot find IConverter class in my program...

Upvotes: 2

Views: 3659

Answers (2)

Matteo Baldi
Matteo Baldi

Reputation: 5828

You're clearly triying to use documents4j, so I suggest you to read carefully the documentation there. It seems you have not included documents4j libraries in your project (you need at least the documents4j-api dependency but I suggest you to give a look at documents4j-local).

You can add the required lib directly with Maven (just add the dependency below) OR get directly the jar.

<dependency> 
<groupId>com.documents4j</groupId> 
<artifactId>documents4j-api</artifactId> 
<version>1.0.2</version> 
<type>pom</type> 
</dependency>

Upvotes: 3

KishanCS
KishanCS

Reputation: 1377

I would like you to try this code as it gives me PDF converter output file i am not sure about accuracy .

InputStream is = new FileInputStream(new File("your Docx PAth"));
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                    .load(is);
            List sections = wordMLPackage.getDocumentModel().getSections();
            for (int i = 0; i < sections.size(); i++) {
                wordMLPackage.getDocumentModel().getSections().get(i)
                        .getPageDimensions();
            }
            Mapper fontMapper = new IdentityPlusMapper();
            PhysicalFont font = PhysicalFonts.getPhysicalFonts().get(
                    "Comic Sans MS");//set your desired font 
            fontMapper.getFontMappings().put("Algerian", font);
            wordMLPackage.setFontMapper(fontMapper);
            PdfSettings pdfSettings = new PdfSettings();
            org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
                    wordMLPackage);
            //To turn off logger
            List<Logger> loggers = Collections.<Logger> list(LogManager
                    .getCurrentLoggers());
            loggers.add(LogManager.getRootLogger());
            for (Logger logger : loggers) {
                logger.setLevel(Level.OFF);
            }
            OutputStream out = new FileOutputStream(new File("Your OutPut PDF path"));
            conversion.output(out, pdfSettings);
            System.out.println("DONE!!");

Hopefully this solution would be fine for your problem. Thank you!!

Upvotes: 0

Related Questions