org.docx4j.Docx4J Java Examples

The following examples show how to use org.docx4j.Docx4J. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WatermarkPicture.java    From kbase-doc with Apache License 2.0 6 votes vote down vote up
public void addBackground(WordprocessingMLPackage wordMLPackage) throws Exception
    {
    	
    	image = this.getImage();

    	BinaryPartAbstractImage imagePartBG = BinaryPartAbstractImage.createImagePart(wordMLPackage, image);
//    	wordMLPackage.getMainDocumentPart().getContents().setBackground(createBackground(imagePartBG.getRelLast().getId()));
    	org.docx4j.wml.CTBackground background = wordMLPackage.getMainDocumentPart().getContents().getBackground();
    	if (background==null) {
    		background = org.docx4j.jaxb.Context.getWmlObjectFactory().createCTBackground();
    	}
//    	background.setColor("FF0000");
    	background.setColor("000000");
    	wordMLPackage.getMainDocumentPart().getContents().setBackground(background);
    	
    	String format = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
    	File file2 = new File("E:\\ConvertTester\\docx\\docx4j_" + format + ".docx");
        Docx4J.save(wordMLPackage, file2);
    }
 
Example #2
Source File: HtmlConverter.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * 将 {@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;
}
 
Example #3
Source File: WordprocessingMLDocxSaxTemplate.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * 变量替换方式实现(只能解决固定模板的word生成)
 * @param template :模板内容
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(InputStream template, Map<String, Object> variables) throws Exception {
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from InputStream");
		wordMLPackage = Docx4J.load(template);
	}
       if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSAXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #4
Source File: WordprocessingMLDocxStAXTemplate.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @param template :模板文件
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(File template, Map<String, Object> variables) throws Exception{
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null || !template.exists() || !template.isFile() ) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from " + template.getAbsolutePath());
		wordMLPackage = Docx4J.load(template);
	}
	if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSaTXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #5
Source File: WordprocessingMLDocxStAXTemplate.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * 变量替换方式实现(只能解决固定模板的word生成)
 * @param template :模板内容
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(InputStream template, Map<String, Object> variables) throws Exception {
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from InputStream");
		wordMLPackage = Docx4J.load(template);
	}
       if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSaTXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #6
Source File: DocxProducer.java    From OfficeProducer with Apache License 2.0 6 votes vote down vote up
/**
 * 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);*/
}
 
Example #7
Source File: WatermarkPicture.java    From kbase-doc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception
    {
    	
		// The image to add
		//imageFile = new File(System.getProperty("user.dir") + "/src/test/resources/images/greentick.png" );  
		
    	// Save it to
		//DOCX_OUT = System.getProperty("user.dir") + "/OUT_WaterMarkPicture.docx";
    	
    	imageFile = new File("E:\\ConvertTester\\images\\jshrss-logo.png");
    	DOCX_OUT = "E:\\ConvertTester\\docx\\NVR5X-I人脸比对配置-ekozhan.docx";

    	WatermarkPicture sample = new WatermarkPicture();
    	

        File f = new File(DOCX_OUT);
//    	wordMLPackage = WordprocessingMLPackage.createPackage();
    	
//        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(f);
        WordprocessingMLPackage wordMLPackage = Docx4J.load(f);
        sample.addWaterMark(wordMLPackage);
//    	sample.addBackground(wordMLPackage);
    }
 
Example #8
Source File: WordprocessingMLPackageWriter.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
 * @param wmlPackage {@link WordprocessingMLPackage} 对象
 * @param output 文件输出流
 * @throws IOException :IO异常
 * @throws Docx4JException : Docx4j异常
 */
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);
       }
}
 
Example #9
Source File: TextBoxTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
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")));
		
	}		
}
 
Example #10
Source File: TblHeaderTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
	 * "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"));
		}
		
		
		
	}
 
Example #11
Source File: TblHeaderTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
	 * "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"));
		}
		
		
	}
 
Example #12
Source File: FOPAreaTreeHelper.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
static org.w3c.dom.Document getAreaTreeViaFOP(WordprocessingMLPackage hfPkg, boolean useXSLT) throws Docx4JException, ParserConfigurationException, SAXException, IOException  {

    	  // Currently FOP dependent!  But an Antenna House version ought to be feasible.
    	
        FOSettings foSettings = Docx4J.createFOSettings();
        foSettings.setWmlPackage(hfPkg);
        foSettings.setApacheFopMime(MimeConstants.MIME_FOP_AREA_TREE);
        
        foSettings.setLayoutMasterSetCalculationInProgress(true); // avoid recursion
        
//        foSettings.getFeatures().add(ConversionFeatures.PP_PDF_APACHEFOP_DISABLE_PAGEBREAK_LIST_ITEM); // in 3.0.1, this is off by default
        
        // Since hfPkg is already a clone, we don't need PP_COMMON_DEEP_COPY
        // Plus it invokes setFontMapper, which does processEmbeddings again, and those fonts aren't much use to us here
        foSettings.getFeatures().remove(ConversionFeatures.PP_COMMON_DEEP_COPY);
        
        if (log.isDebugEnabled()) {
        	foSettings.setFoDumpFile(new java.io.File(System.getProperty("user.dir") + "/hf.fo"));
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        if (useXSLT) {
        	Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
        } else {
        	Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);        	
        }
        
        InputStream is = new ByteArrayInputStream(os.toByteArray());
		DocumentBuilder builder = XmlUtils.getNewDocumentBuilder();
		return builder.parse(is);

    }
 
Example #13
Source File: WordToHtmlRenditionProvider.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #14
Source File: WordprocessingMLPackageWriter.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 docx
 * @param wmlPackage {@link WordprocessingMLPackage} 对象
 * @param output 文件输出流
 * @throws IOException :IO异常
 * @throws Docx4JException : Docx4j异常
 */
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);
       }
}
 
Example #15
Source File: WordprocessingMLTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @param template :模板文件流
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
default WordprocessingMLPackage process(InputStream template, Map<String, Object> variables) throws Exception{
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from InputStream");
		wordMLPackage = Docx4J.load(template);
	}
	return wordMLPackage;
}
 
Example #16
Source File: WordprocessingMLTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @param template :模板文件
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
default WordprocessingMLPackage process(File template, Map<String, Object> variables) throws Exception{
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null || !template.exists() || !template.isFile() ) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from " + template.getAbsolutePath());
		wordMLPackage = Docx4J.load(template);
	}
	return wordMLPackage;
}
 
Example #17
Source File: WordprocessingMLDocxTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * 变量替换方式实现(只能解决固定模板的word生成)
 * @param template :模板内容
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(InputStream template, Map<String, Object> variables) throws Exception {
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from InputStream");
		wordMLPackage = Docx4J.load(template);
	}
       if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
           // 获取静态变量集合
           HashMap<String, String> staticMap = getStaticData(variables);
           // 替换普通变量  
           documentPart.variableReplace(staticMap);  
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #18
Source File: WordprocessingMLDocxTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @param template :模板文件
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(File template, Map<String, Object> variables) throws Exception{
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null || !template.exists() || !template.isFile() ) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from " + template.getAbsolutePath());
		wordMLPackage = Docx4J.load(template);
	}
	if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
           // 获取静态变量集合
           HashMap<String, String> staticMap = getStaticData(variables);
           // 替换普通变量  
           documentPart.variableReplace(staticMap);  
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #19
Source File: WordprocessingMLDocxSaxTemplate.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @param template :模板文件
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(File template, Map<String, Object> variables) throws Exception{
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null || !template.exists() || !template.isFile() ) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from " + template.getAbsolutePath());
		wordMLPackage = Docx4J.load(template);
	}
	if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSAXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #20
Source File: WordprocessingMLPackageWriter.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
 * @param wmlPackage {@link WordprocessingMLPackage} 对象
 * @param output 文件输出流
 * @throws IOException :IO异常
 * @throws Docx4JException : Docx4j异常
 */
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);
       }
}
 
Example #21
Source File: WordToPdfRenditionProvider.java    From spring-content with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example #22
Source File: DocxProducer.java    From OfficeProducer with Apache License 2.0 4 votes vote down vote up
/**
 * 保存当前Docx文件
 */
private static void saveDocx(WordprocessingMLPackage wordMLPackage,
                             String savePath)
        throws FileNotFoundException, Docx4JException {
    Docx4J.save(wordMLPackage, new File(savePath), Docx4J.FLAG_SAVE_ZIP_FILE);
}
 
Example #23
Source File: Docx4jUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public static void toP(WordprocessingMLPackage wordMLPackage,String outPath) throws Exception{
    OutputStream os = new FileOutputStream(outPath);
    FOSettings foSettings = Docx4J.createFOSettings();
    foSettings.setWmlPackage(wordMLPackage);
    Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
}
 
Example #24
Source File: Conversion.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
public void outputXSLFO(OutputStream os, PdfSettings settings) throws Docx4JException {
	setupSettings(settings, FOSettings.MIME_PDF);
	Docx4J.toFO(settings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
}
 
Example #25
Source File: DocToPDFConverter.java    From docs-to-pdf-converter with MIT License 4 votes vote down vote up
@Override
public void convert() throws Exception{

	loading();

	InputStream iStream = inStream;


	WordprocessingMLPackage wordMLPackage = getMLPackage(iStream);


	processing();
	Docx4J.toPDF(wordMLPackage, outStream);

	finished();
	
}
 
Example #26
Source File: Conversion.java    From docx4j-export-FO with Apache License 2.0 2 votes vote down vote up
/** Create a pdf version of the document, using XSL FO. 
 * 
 * @param os
 *            The OutputStream to write the pdf to 
 * @param settings
 *            The configuration for the conversion 
 * 
 * */     
public void output(OutputStream os, PdfSettings settings) throws Docx4JException {
	setupSettings(settings, FOSettings.INTERNAL_FO_MIME);
	Docx4J.toPDF(wordMLPackage, os);
}