本文整理汇总了Java中org.docx4j.Docx4J类的典型用法代码示例。如果您正苦于以下问题:Java Docx4J类的具体用法?Java Docx4J怎么用?Java Docx4J使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Docx4J类属于org.docx4j包,在下文中一共展示了Docx4J类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: convertDocxToPDF
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* docx文档转换为PDF
*
* @param wordMLPackage
* @param pdfPath PDF文档存储路径
* @throws Exception
*/
public static void convertDocxToPDF(WordprocessingMLPackage wordMLPackage,
String pdfPath)
throws Exception {
//HashSet<String> features = new HashSet<>();
//features.add(PP_PDF_APACHEFOP_DISABLE_PAGEBREAK_LIST_ITEM);
//WordprocessingMLPackage process = Preprocess.process(wordMLPackage, features);
FileOutputStream fileOutputStream = new FileOutputStream(pdfPath);
Docx4J.toPDF(wordMLPackage, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
/*FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wordMLPackage);
Docx4J.toFO(foSettings, fileOutputStream, Docx4J.FLAG_EXPORT_PREFER_XSL);*/
}
示例2: savePdf
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
*
* @param wordMLPackage
* @return
* @throws Exception
*/
public File savePdf(WordprocessingMLPackage wordMLPackage) throws Exception {
File file = new File(genFilePath() + ".pdf");
OutputStream os = new java.io.FileOutputStream(file);
Docx4J.toPDF(wordMLPackage, os);
os.flush();
os.close();
if (logger.isDebugEnabled()) {
logger.debug("Save to [.pdf]: {}", file.getAbsolutePath());
}
return file;
}
示例3: convert
import org.docx4j.Docx4J; //导入依赖的package包/类
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
try {
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource);
// Refresh the values of DOCPROPERTY fields
FieldUpdater updater = new FieldUpdater(pkg);
updater.update(true);
AbstractHtmlExporter exporter = new HtmlExporterNG2();
HTMLSettings htmlSettings= Docx4J.createHTMLSettings();
htmlSettings.setImageDirPath("/tmp/sample-docx.html_files");
htmlSettings.setImageTargetUri("/tmp/_files");
htmlSettings.setWmlPackage(pkg);
Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
OutputStream os = new FileOutputStream("/tmp/temp.html");
Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
IOUtils.closeQuietly(os);
if (pkg.getMainDocumentPart().getFontTablePart()!=null) {
pkg.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
}
// This would also do it, via finalize() methods
htmlSettings = null;
pkg = null;
return new FileInputStream("/tmp/temp.html");
} catch (Exception e) {
}
return null;
}
示例4: convertPDF
import org.docx4j.Docx4J; //导入依赖的package包/类
@Override
public File convertPDF(File theFile, String md5UploadedFile) throws PDFConverterException {
try {
WordprocessingMLPackage wordMLPckg = Docx4J.load(theFile);
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wordMLPckg);
String outFileName = this.getOutputFileName(md5UploadedFile);
File outputFile = new File(Config.getString("application.staticFiles"), outFileName);
FileOutputStream pdfStream = new FileOutputStream(outputFile);
Docx4J.toFO(foSettings, pdfStream, Docx4J.FLAG_EXPORT_PREFER_XSL);
pdfStream.close();
return outputFile;
} catch (Exception e) {
log.error("Fail to create PDF in DOC4J Converter", e);
throw new PDFConverterException("Fail to create PDF in DOC4J Converter", e);
}
}
示例5: writeToDocx
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 docx
*/
public void writeToDocx(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
Assert.notNull(wmlPackage, " wmlPackage is not specified!");
Assert.notNull(output, " output is not specified!");
try {
wmlPackage.save(output , Docx4J.FLAG_SAVE_ZIP_FILE );//保存到 docx 文件
} finally{
IOUtils.closeQuietly(output);
}
}
示例6: writeToPDF
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
*/
public void writeToPDF(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
Assert.notNull(wmlPackage, " wmlPackage is not specified!");
Assert.notNull(output, " output is not specified!");
try {
Docx4J.toPDF(wmlPackage, output); //保存到 pdf 文件
output.flush();
} finally{
IOUtils.closeQuietly(output);
}
}
示例7: convert
import org.docx4j.Docx4J; //导入依赖的package包/类
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
try {
// Font regex (optional)
// Set regex if you want to restrict to some defined subset of fonts
// Here we have to do this before calling createContent,
// since that discovers fonts
String regex = null;
// Windows:
// String
// regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
//regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
// Mac
// String
// regex=".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*";
PhysicalFonts.setRegex(regex);
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource);
// Refresh the values of DOCPROPERTY fields
FieldUpdater updater = new FieldUpdater(pkg);
updater.update(true);
// FO exporter setup (required)
// .. the FOSettings object
FOSettings foSettings = Docx4J.createFOSettings();
// if (false) {
// foSettings.setFoDumpFile(new java.io.File("/tmp/test.fo"));
// }
foSettings.setWmlPackage(pkg);
//ByteArrayOutputStream os = new ByteArrayOutputStream();
String outputfilepath;
outputfilepath = "/tmp/temp.pdf";
OutputStream os = new java.io.FileOutputStream(outputfilepath);
// Specify whether PDF export uses XSLT or not to create the FO
// (XSLT takes longer, but is more complete).
// Don't care what type of exporter you use
Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
if (pkg.getMainDocumentPart().getFontTablePart()!=null) {
pkg.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
}
return new FileInputStream(outputfilepath);
} catch (Exception e) {
}
return null;
}
示例8: testTblHeaderOne
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* "fo:table" content model is: (marker*,table-column*,table-header?,table-footer?,table-body+)
*
* so a table with just a table header should have
* that converted to table-body row.
*/
@Test
public void testTblHeaderOne() throws Exception {
String inputfilepath = System.getProperty("user.dir") + "/src/test/resources/tables/tblHeaderTestOne.docx";
WordprocessingMLPackage wordMLPackage= WordprocessingMLPackage.load(new java.io.File(inputfilepath));
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wordMLPackage);
// want the fo document as the result.
foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
// exporter writes to an OutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Don't care what type of exporter you use
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_NONE);
//Prefer the exporter, that uses a xsl transformation
Docx4J.toFO(foSettings, baos, Docx4J.FLAG_EXPORT_PREFER_XSL);
byte[] bytes = baos.toByteArray();
// System.out.println(new String(bytes, "UTF-8"));
// Now use XPath to assert it has a table-body
try {
org.w3c.dom.Document domDoc = w3cDomDocumentFromByteArray( bytes);
assertTrue(this.isAbsent(domDoc, "//fo:table-header"));
assertTrue(this.isPresent(domDoc, "//fo:table-body"));
} catch (SAXParseException e) {
Assert.fail(e.getMessage());
Assert.fail(new String(bytes, "UTF-8"));
}
}
示例9: testTblHeaderTwo
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* "fo:table" content model is: (marker*,table-column*,table-header?,table-footer?,table-body+)
*
* so a table with body rows before header rows should have
* those body rows converted to header rows.
*/
@Test
public void testTblHeaderTwo() throws Exception {
String inputfilepath = System.getProperty("user.dir") + "/src/test/resources/tables/tblHeaderTestTwo.docx";
WordprocessingMLPackage wordMLPackage= WordprocessingMLPackage.load(new java.io.File(inputfilepath));
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wordMLPackage);
// want the fo document as the result.
foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
// exporter writes to an OutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Don't care what type of exporter you use
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_NONE);
//Prefer the exporter, that uses a xsl transformation
Docx4J.toFO(foSettings, baos, Docx4J.FLAG_EXPORT_PREFER_XSL);
byte[] bytes = baos.toByteArray();
// System.out.println(new String(bytes, "UTF-8"));
// Now use XPath to assert it has a table-body
try {
org.w3c.dom.Document domDoc = w3cDomDocumentFromByteArray( bytes);
assertTrue(this.isAbsent(domDoc, "//fo:table-body[following-sibling::fo:table-header]"));
assertTrue(this.isPresent(domDoc, "//fo:table-header[following-sibling::fo:table-body]"));
} catch (SAXParseException e) {
Assert.fail(e.getMessage());
Assert.fail(new String(bytes, "UTF-8"));
}
}
示例10: execute
import org.docx4j.Docx4J; //导入依赖的package包/类
private static void execute(WordprocessingMLPackage wordMLPackage) throws Docx4JException, IOException {
// Pretty print the main document part
System.out.println(
XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true) );
// Optionally save it
if (save) {
String filename = System.getProperty("user.dir") + "/OUT_CreateWordprocessingMLDocument.docx";
wordMLPackage.save(new File(filename) );
System.out.println("Saved " + filename);
}
// FO
if (fo) {
OutputStream baos = new ByteArrayOutputStream();
Exporter<FOSettings> exporter = FOExporterVisitor.getInstance();
FOSettings settings = new FOSettings();
settings.setWmlPackage(wordMLPackage);
settings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
exporter.export(settings, baos);
System.out.println( ((ByteArrayOutputStream) baos).toString("UTF-8"));
} else {
Docx4J.toPDF(wordMLPackage,
FileUtils.openOutputStream(new File(System.getProperty("user.dir") + "/OUT_textbox.pdf")));
}
}
示例11: convertToDocXThenPdf
import org.docx4j.Docx4J; //导入依赖的package包/类
public static void convertToDocXThenPdf(File html, File pdf) throws IOException, Docx4JException, JAXBException {
// Create an empty docx package
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();
XHTMLImporterImpl xHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
xHTMLImporter.setHyperlinkStyle("Hyperlink");
// Convert the XHTML, and add it into the empty docx we made
wordMLPackage.getMainDocumentPart().getContent().addAll(xHTMLImporter.convert(html, null));
//wordMLPackage.save( docx );
String regex = null;
PhysicalFonts.setRegex(regex);
try {
wordMLPackage.setFontMapper(new IdentityPlusMapper());
} catch (Exception e) {
e.printStackTrace();
}
// All methods write to an output stream
OutputStream os = new java.io.FileOutputStream(pdf);
// Refresh the values of DOCPROPERTY fields
FieldUpdater updater = new FieldUpdater(wordMLPackage);
updater.update(true);
Docx4J.toPDF(wordMLPackage, os);
System.out.println("Saved: " + pdf.getAbsolutePath());
// Clean up, so any ObfuscatedFontPart temp files can be deleted
if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) {
wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
}
}
示例12: writeAsPDF
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* Writes this document as PDF to a OutputStream and closed the stream in
* any case.
*
* @param out
* - the Outputstream to write the document.
* @throws IOException
*/
public void writeAsPDF(OutputStream out) throws IOException {
WordprocessingMLPackage mlPackage = getWordMLPackage();
try {
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(mlPackage);
Docx4J.toFO(foSettings, out, Docx4J.FLAG_EXPORT_PREFER_XSL);
} catch (Exception e) {
throw new WteException("Unable to create PDF Document", e);
} finally {
out.close();
}
}
示例13: exportReport
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* Export the items in the given output
*
* @param document W3C XML DOM document
* @param personBean current user
* @param locale
* current locale
* @param parameters
* the directory of the DOCX template enriched with special placeholders
* @param os
* the output stream to write to
* @param contextMap
* @param description
*/
@Override
public void exportReport(Document document,
TPersonBean personBean,
Locale locale,
Map<String, Object> parameters,
OutputStream os,
Map<String, Object> contextMap,
Map<String, Object> description)
throws ReportExportException {
String format= (String) description.get(IDescriptionAttributes.FORMAT);
if (format == null || !format.equals(FORMAT_DOCX)) {
throw new ReportExportException(ERROR_UNKNOWN_FORMAT);
}
/* Caution! Because the me
* based on the template file name, the template has to be uploaded in the wiki!
*/
String docxTemplatePath = null;
URL completeURL = (URL)parameters.get(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL);
if (completeURL!=null) {
docxTemplatePath = completeURL.getFile();
WordprocessingMLPackage wpMLP = AssembleWordprocessingMLPackage.getWordMLPackage(
MeetingDatasource.WORK_ITEM_BEAN, MeetingDatasource.REPORT_BEANS,
docxTemplatePath, personBean.getObjectID(), locale);
try {
Docx4J.save(wpMLP, os, Docx4J.FLAG_NONE);
} catch (Exception e) {
LOGGER.error("Exporting the docx failed with throwable " + e.getMessage());
LOGGER.debug(ExceptionUtils.getStackTrace(e));
}
}
}
示例14: writeToPDFWhithFo
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
*/
public void writeToPDFWhithFo(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
Assert.notNull(wmlPackage, " wmlPackage is not specified!");
Assert.notNull(output, " output is not specified!");
try {
// Font regex (optional)
// Set regex if you want to restrict to some defined subset of fonts
// Here we have to do this before calling createContent,
// since that discovers fonts
//String regex = null;
// Refresh the values of DOCPROPERTY fields
FieldUpdater updater = new FieldUpdater(wmlPackage);
updater.update(true);
// .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
// eg Glyph "ي" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
// eg Glyph "ج" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
// to a font which does
PhysicalFonts.get("Arial Unicode MS");
// FO exporter setup (required)
// .. the FOSettings object
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wmlPackage);
foSettings.setApacheFopMime("application/pdf");
// Document format:
// The default implementation of the FORenderer that uses Apache Fop will output
// a PDF document if nothing is passed via
// foSettings.setApacheFopMime(apacheFopMime)
// apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
// FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
//foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
// Specify whether PDF export uses XSLT or not to create the FO
// (XSLT takes longer, but is more complete).
// Don't care what type of exporter you use
Docx4J.toFO(foSettings, output, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Prefer the exporter, that uses a xsl transformation
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
// faster, but not yet at feature parity
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);
// Clean up, so any ObfuscatedFontPart temp files can be deleted
// if (wordMLPackage.getMainDocumentPart().getFontTablePart()!=null) {
// wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
// }
// This would also do it, via finalize() methods
updater = null;
foSettings = null;
wmlPackage = null;
} finally{
IOUtils.closeQuietly(output);
}
}
示例15: saveDocx
import org.docx4j.Docx4J; //导入依赖的package包/类
/**
* 保存当前Docx文件
*/
private static void saveDocx(WordprocessingMLPackage wordMLPackage,
String savePath)
throws FileNotFoundException, Docx4JException {
Docx4J.save(wordMLPackage, new File(savePath), Docx4J.FLAG_SAVE_ZIP_FILE);
}