welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

doc2pdf word转换至pdf文档服务


分类 Java   关键字 分享   标签 java   web   linux   发布 hongwei  1441037637304
注意 转载须保留原文链接,译文链接,作者译者等信息。  
WordUtil便于填充word模板文件,然后调用openoffice转换至pdf的效果较好,java代码引用jodconverter依赖即可。

测试地址:
http://cms.xlongwei.com/open/doc2pdf.html
测试的doc地址:http://cms.xlongwei.com/uploads/temp/word/contract_1441036702250.doc
生成的pdf地址:http://cms.xlongwei.com/uploads/temp/pdf/contract_1441036702250.pdf



生成效果相当不错:(里面的空格和表格都方便调用WordUtil填充)


OpenController代码:
@Controller
@RequestMapping("open")
public class OpenController {
	@Autowired UploadController uploadController;
	
	private String[] wordExts = {"doc","docx"};//word有很多种格式
	private Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping(value="doc2pdf",method=RequestMethod.GET)
	public String doc2pdf() {
		return "open/doc2pdf";
	}
	
	@RequestMapping(value="doc2pdf.html",method=RequestMethod.POST)
	public Object doc2pdf(HttpServletRequest request, Model model, MultipartFile doc) {
		JSONObject json = doc2pdf(request, doc);
		if(json.containsKey("error")) {
			model.addAttribute("error", json.get("error"));
		}else if(json.containsKey("path")) {
			model.addAttribute("domain", json.get("domain"));
			model.addAttribute("path", json.get("path"));
		}
		return "open/doc2pdf";
	}
	//支持HttpClient方式调用接口,返回domain,path
	@ResponseBody
	@RequestMapping(value="doc2pdf.json",method=RequestMethod.POST)
	public JSONObject doc2pdf(HttpServletRequest request, MultipartFile doc) {
		JSONObject json = new JSONObject();
		String ext = FileUtil.getFileExt(doc.getOriginalFilename());
		if(ArrayUtils.contains(wordExts, ext)==false) {
			json.put("error", "file ext: "+ext+" is not one of "+Arrays.toString(wordExts));
		}else {
			String upload = (String)uploadController.temp("word", doc);
			upload = StringUtils.newStringUtf8(StringUtils.getBytesIso8859_1(upload));
			logger.info("word2pdf upload: "+upload);
			
			String[] path = upload.split(",");
			String domain = path[0], wordPath = path[1];
			String pdfPath = "pdf/"+FileUtil.getFileName(wordPath)+".pdf";
			
			File docFile = new File(GlobalConfig.getProperty(UploadUtil.uploads_temp_file), wordPath);
			File pdfFile = new File(GlobalConfig.getProperty(UploadUtil.uploads_temp_file), pdfPath);
			boolean doc2pdf = PdfUtil.doc2pdf(docFile, pdfFile);//直接调用上一篇文章的PdfUtil
			if(doc2pdf==false) {
				json.put("error", "PdfUtil.doc2pdf failed and return false");
			}else {
				logger.info("doc2pdf convert success: "+pdfPath);
				json.put("domain",domain);
				json.put("path",pdfPath);
			}
		}
		return json;
	}
}