[英]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: 我正在寻找在Java中将docx
文件转换为pdf
的最佳方法,这是我尝试过的方法:
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... 问题是我在程序中找不到IConverter类。
You're clearly triying to use documents4j , so I suggest you to read carefully the documentation there. 您显然正在尝试使用document4j ,所以我建议您仔细阅读该文档。 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
). 看来您的项目中没有包含documents4j
库(您至少需要documents4j-api
依赖项,但我建议您看一下documents4j-local
)。
You can add the required lib directly with Maven
(just add the dependency below) OR get directly the jar . 您可以直接使用Maven
添加所需的lib(只需在下面添加依赖项),或直接获取jar 。
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-api</artifactId>
<version>1.0.2</version>
<type>pom</type>
</dependency>
I would like you to try this code as it gives me PDF converter output file i am not sure about accuracy . 我希望您尝试这段代码,因为它给我PDF转换器输出文件,我不确定准确性。
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!! 谢谢!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.