`
01jiangwei01
  • 浏览: 533803 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

docx4j word转pdf

 
阅读更多

使用docx4j转pdf,代码及模板在下面。模板在附件中,字体使用的是宋体。

 

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import org.docx4j.Docx4J;
import org.docx4j.TraversalUtil;
import org.docx4j.XmlUtils;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.finders.ClassFinder;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.model.datastorage.migration.VariablePrepare;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tr;

/**
 * 
 * 将模板内容替换后转化成PDF输出
 *
 */
public class MyexapmleConvertToPDF {

private static final  String templetate_docx  = "\\myexamples\\replace_text_PDF_templetate.docx";
	
	private static final  String output_pdf  = "\\myexamples\\replace_text_PDF.pdf";
	
	public static void main(String[] args) throws Exception {
		//加载模板
				WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
						.load(new java.io.File(System.getProperty("user.dir")+templetate_docx));

				//准备数据
				HashMap<String, String> mappings = new HashMap<String, String>();
				mappings.put("username", "张三");
				mappings.put("party_date", "2014年10月25日");
				mappings.put("numberCount", "150");
				mappings.put("pay_acount", "99.50");
				mappings.put("now_date", "2014年09月25日");
				
				//进行数据合并
				MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
		 
				ClassFinder finder = new ClassFinder(Tbl.class); // <----- change this to suit
				new TraversalUtil(documentPart.getContent(), finder);
				//查找模板表格(第i个表格 )
				int seleTableIndex = 0;
				Tbl table_selected =  (Tbl) finder.results.get(seleTableIndex);
				List trs = table_selected.getContent(); 
				//模板行,第2行为模板行
				int table_templetate_row_index = 2;
				org.docx4j.wml.Tr templetate_row = (Tr)trs.get(table_templetate_row_index);
				String templetate_row_string = XmlUtils.marshaltoString(templetate_row,true,true);
				//System.out.println(templetate_row_string);
				//替换第二行的数据
				List<Object>tds = templetate_row.getContent();
				HashMap datamap = new HashMap();
				datamap.put("table_index", "1");
				datamap.put("product_name", "唐代陶瓷");
			 
				
				HashMap datamap2 = new HashMap();
				datamap2.put("table_index", "2");
				datamap2.put("product_name", "明代王冠"); 
				
				//合并表格数据1
				Object newTr = XmlUtils.unmarshallFromTemplate(templetate_row_string,datamap);
				table_selected.getContent().add(newTr);
				//合并表格数据2
				newTr = XmlUtils.unmarshallFromTemplate(templetate_row_string,datamap2);
				table_selected.getContent().add(newTr);
				//移除第2行
				table_selected.getContent().remove(table_templetate_row_index);
					
				//数据替换预处理,调用API包
				//在表格替换后调用这个方法
				VariablePrepare.prepare(wordMLPackage);
				documentPart.variableReplace(mappings);
	 
		//pdf准备工作
		// 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=".*(simsunb|simsun|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);
		
		// Set up font mapper (optional)
		Mapper fontMapper = new IdentityPlusMapper();
		
		// .. 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
		PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("calibri"); 
			// make sure this is in your regex (if any)!!!
		if (font!=null) {
			fontMapper.getFontMappings().put("Times New Roman", font);
		}
		fontMapper.getFontMappings().put("Libian SC Regular", PhysicalFonts.getPhysicalFonts().get("SimSun"));
		wordMLPackage.setFontMapper(fontMapper);
		// FO exporter setup (required)
		// .. the FOSettings object
    	FOSettings foSettings = Docx4J.createFOSettings();
    	 
    	foSettings.setFoDumpFile(new java.io.File(System.getProperty("user.dir")+templetate_docx + ".fo"));
    	
		foSettings.setWmlPackage(wordMLPackage);
		
		// 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);
		
		// exporter writes to an OutputStream.		
		OutputStream os = new java.io.FileOutputStream(System.getProperty("user.dir")+output_pdf);
    	
		// 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);
		
		// 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);
		System.out.println("创建完成 " );

	}

}

 

其中代码字体需要注意了。

regex=".*(simsunb|simsun|calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";

 其中的名称获取方式是在c://windows/fonts目录下找到需要的文字。右键-属性 查看其名称。Linux没有试过。自己测试。

如下截图:

 

 

 

  • 大小: 636.8 KB
分享到:
评论

相关推荐

    利用docx4j实现docx转pdf

    利用docx4j实现docx转pdf小dome

    word转pdf所用docx4j

    docx4j 用的jar包,docx4j学习网址:http://www.docx4java.org/trac/docx4j

    docx4j word合并转pdf.zip

    使用docx4j相关jar包,实现多个word文档合并,并转为pdf文档格式

    word转pdf、word导出、pdf加水印

    1、使用freemaker对模板解析填充数据导出word文档的功能 2、实现使用itext对word转pdf功能 3、实现了对pdf加水印功能

    word转pdf并加水印

    word转pdf并加水印示例

    docx4j所需jar包全

    docx4j所需jar包整合,其中word转pdf,word转html,word中docx转doc,java代码实现,都可以使用,仅限学习参考使用。

    docx4j(jar,src,依赖JAR)

    docx4j,jar,源码,依赖包,3.2.2

    docx4j以及依赖的全套jar包

    可以使用docx4j进行多个word文档的合并,word转Pdf等,这套完整的jar包可以让我们在开发过程中不必在为jar包的缺失而烦恼

    Word转pdf java实现

    word转pdf,分别使用xdocreport和docx4j实现

    docx4j-3.3.6

    Export as PDF (using Plutext's PDF Converter, or use docx4j-export-FO project) Produce/consume Word 2007's xmlPackage (pkg) format Apply transforms, including common filters Font support (font ...

    docx4j所有jar包

    docx4j所有的jar包,设计到word转换pdf,和他的所有依赖包

    docx4j 3.3.0 jar 包

    docx4j是Java操作office2007+中的Word、Excel、PPT的开源项目,其主要针对WordXML同时也可以处理Excel和PPT,比POI要强大很多(POI对Word2007支持很弱)

    documents4j,documents4j是一个java库,用于将文档转换为另一种文档格式.zip

    documents4j是一个用于将...documents4j附带了对ms-word和ms-excel for windows的修改,例如,允许将docx文件转换为pdf文件,而不必对生成的文档进行常见的扭曲,这些扭曲通常是在使用非微软产品进行转换时观察到的。

    docx4j-2.6.0-api.zip

    作为docx保存docx到文件系统(zipped)或者保存到JCR(unzipped) 应用转换,包括常见过滤器 作为HTML或者PDF导出 比较文档、段落或者sdt(内容控件)之间的差异 字体支持(字体替换及使用任何文档中嵌入的字体)

    转pdf需要到的jar包.zip

    将word文档转化为PDF是项目中常见的需求之一,目前主流的方法可以分为两大类,一类是利用各种Office应用进行转换,譬如Microsoft Office、WPS以及LiberOffice,另一种是利用各种语言提供的对于Office文档读取的接口...

    导出PDF插件(表格没有线框)

    可以导出PDF,但是导出的PDF中,表格没有线框

    aspose-word2pdf-15.8.0-jdk16.zip

    Java利用aspose将word文档转换成pdf格式等全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换

    Downloads.zip

    docx4j 转pdf所有需jar

    PDF全格式转换工具

    Ailt PDF to All Document Converter(PDF转换工具)是个实用的工具,可用于将PDF格式文件转换成Word, Excel, PowerPoint, SWF, image等格式的文件。 目前该软件已支持转换成DOC, DOCX, DOCM, RTF, XLS, XLSX, XLSM, ...

Global site tag (gtag.js) - Google Analytics