在业务上遇到了这种要把上传的word文件转成pdf的实现。在网上找了一堆乱七八糟的也不知道什么玩意,最后得出用aspose第三方插件实现最好,其他的都太乱了,poi插件什么的都没成功,报错搞不了。
最后是aspose插件成功了,如下:
1、首页pom.xml文件引入aspose插件:
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose.slides</artifactId> <version>15.9.0</version> </dependency> <dependency> <groupId>com.aspose</groupId> <artifactId>aspose-cells</artifactId> <version>8.5.2</version> </dependency> <dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>16.8.0</version> <classifier>jdk16</classifier> </dependency>
2、准备一个 license.xml 文件,工具类中要用到:(新建license.xml文件 (放入Springboot项目的resources目录下))
<License> <Data> <Products> <Product>Aspose.Total for Java</Product> <Product>Aspose.Words for Java</Product> </Products> <EditionType>Enterprise</EditionType> <SubscriptionExpiry>20991231</SubscriptionExpiry> <LicenseExpiry>20991231</LicenseExpiry> <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber> </Data> <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature> </License>
3、写个word转pdf的工具类:AsposeWordToPdfUtil.jav
package org.springblade.core.tool.utils; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import com.aspose.words.Document; import com.aspose.words.DocumentBuilder; import com.aspose.words.HeaderFooter; import com.aspose.words.HeaderFooterType; import com.aspose.words.License; import com.aspose.words.Paragraph; import com.aspose.words.RelativeHorizontalPosition; import com.aspose.words.RelativeVerticalPosition; import com.aspose.words.SaveFormat; import com.aspose.words.Section; import com.aspose.words.Shape; import com.aspose.words.ShapeType; import com.aspose.words.WrapType; import org.springblade.framework.utils.simple.LogUtil; /** * * 由于ASPOSE比较吃内存,操作大一点的文件就会堆溢出,所以请先设置好java虚拟机参数:-Xms512m -Xmx512m(参考值)<br> * 如有疑问,请在CSDN下载界面留言,或者联系QQ569925980<br> * * @author Spark * */ public class AsposeWordToPdfUtil { private InputStream license; private InputStream word; /** * 获取license * * @return */ private boolean getLicense(String filePath) { boolean result = false; try { //license = AsposeWordToPdfUtil.class.getClassLoader().getResourceAsStream("\\asposeLicense.xml");// license路径
//获取Springboot项目中resources目录下的license.xml
InputStream is = AsposeExcelToPDF.class.getClassLoader().getResourceAsStream("license.xml");
File file = new File(filePath); word = new FileInputStream(file); // AsposeWordToPdfUtil.class.getClassLoader().getResourceAsStream( // "\\test_image.docx");// 原始word路径 License aposeLic = new License(); aposeLic.setLicense(license); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * * Inserts a watermark into a document. * * @param doc * The input document. * @param watermarkText * Text of the watermark. * */ private void insertWatermarkText(Document doc, String watermarkText) throws Exception { // Create a watermark shape. This will be a WordArt shape. // You are free to try other shape types as watermarks. Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT); // Set up the text of the watermark. watermark.getTextPath().setText(watermarkText); watermark.getTextPath().setFontFamily("Arial"); /*watermark.setWidth(500); watermark.setHeight(100);*/ watermark.setWidth(100); watermark.setHeight(10); // Text will be directed from the bottom-left to the top-right corner. //watermark.setRotation(-40); // Remove the following two lines if you need a solid black text. watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more // Word-style watermark watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more // Word-style watermark // Place the watermark in the page center. watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); watermark.setWrapType(WrapType.NONE); /*watermark.setVerticalAlignment(VerticalAlignment.CENTER); watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);*/ watermark.setVerticalAlignment(0); watermark.setHorizontalAlignment(0); // Create a new paragraph and append the watermark to this paragraph. Paragraph watermarkPara = new Paragraph(doc); watermarkPara.appendChild(watermark); // Insert the watermark into all headers of each document section. for (Section sect : doc.getSections()) { // There could be up to three different headers in each section, // since we want // the watermark to appear on all pages, insert into all headers. insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY); insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST); insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN); } } /** * 插入水印 * * @param watermarkPara * @param sect * @param headerType * @throws Exception */ private void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception { HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType); if (header == null) { // There is no header of the specified type in the current section, // create it. header = new HeaderFooter(sect.getDocument(), headerType); sect.getHeadersFooters().add(header); } // Insert a clone of the watermark into the header. header.appendChild(watermarkPara.deepClone(true)); } /** * 移除全部水印 * * @param doc * @throws Exception */ private void removeWatermark(Document doc) throws Exception { for (Section sect : doc.getSections()) { // There could be up to three different headers in each section, // since we want // the watermark to appear on all pages, insert into all headers. removeWatermarkFromHeader(sect, HeaderFooterType.HEADER_PRIMARY); removeWatermarkFromHeader(sect, HeaderFooterType.HEADER_FIRST); removeWatermarkFromHeader(sect, HeaderFooterType.HEADER_EVEN); } } /** * 移除指定Section的水印 * * @param sect * @param headerType * @throws Exception */ private void removeWatermarkFromHeader(Section sect, int headerType) throws Exception { HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType); if (header != null) { header.removeAllChildren(); } } private void insertInMage(Document doc, String mageFilePath) throws Exception { /* DocumentBuilder builder2 = new DocumentBuilder(doc); BufferedImage image = ImageIO.read(new FileInputStream(mageFilePath)); // 输出图象文件二进制数制 builder2.moveToBookmark("userimage"); builder2.insertImage(image, 90, 90);*/ DocumentBuilder builder = new DocumentBuilder(doc); // The best place for the watermark image is in the header or footer so it is shown on every page. builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); // Insert a floating picture. BufferedImage image = ImageIO.read(new File(mageFilePath)); Shape shape = builder.insertImage(image); shape.setWrapType(WrapType.NONE); shape.setBehindText(true); shape.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); shape.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); // Calculate image left and top position so it appears in the centre of the page. //shape.setLeft((builder.getPageSetup().getPageWidth() - shape.getWidth()) / 2); //shape.setTop((builder.getPageSetup().getPageHeight() - shape.getHeight()) / 2); shape.setLeft(0); shape.setTop(0); } /** * 将文件另存为其他格式 * @param oldFilePath 旧文件路径,如:c:\aa.doc * @param newFilePath 新文件路径,如:c:\bb.pdf * @param saveFormat 保存格式:com.aspose.words.SaveFormat 进行选择 * @param insertMage 是否插入水印 * @param mageContent 水印内容:可以是文字或图片路径 * @param mageType 水印类别(0文字,1图片) * @param delOldFile 是否删除旧文件 */ public void saveAS(String oldFilePath, String newFilePath, int saveFormat, boolean insertMage, String mageContent, int mageType, boolean delOldFile) { try { getLicense(oldFilePath); long old = System.currentTimeMillis(); Document doc = new Document(word); if (insertMage) { if (mageType == 0) { insertWatermarkText(doc, mageContent +" "); } else { insertInMage(doc, mageContent); } } doc.save(newFilePath, saveFormat); word.close(); if (delOldFile) { File oldFile = new File(oldFilePath); oldFile.delete(); } long now = System.currentTimeMillis(); LogUtil.printLog("共耗时:" + ((now - old) / 1000.0) + "秒\n\n"); } catch (Exception e) { e.printStackTrace(); } } /** * * @param args */ public static void main(String[] args) { AsposeWordToPdfUtil asposeWordToPdf = new AsposeWordToPdfUtil(); // asposeWordToPdf.saveAS("E:\\temp\\cecece.pptx","E:\\temp\\ceshi3.pdf", SaveFormat.PDF, false, // "360安全浏览器下载",0, false); /* * // 验证License if (!asposeTestWord.getLicense( * "C:/Users/fumingzheng/Desktop/国文慧典安装手册--9.6-1.doc")) { return; } * * try { long old = System.currentTimeMillis(); Document doc = new * Document(asposeTestWord.word); //insertInMage(doc); * doc.save("d:\\aaa.pdf", SaveFormat.PDF); * * long now = System.currentTimeMillis(); // LogUtil.printLog("共耗时:" + * ((now - old) / 1000.0) + "秒\n\n" + // "文件保存在:" + file.getPath()); } * catch (Exception e) { e.printStackTrace(); } */ //================1、测试word转pdf asposeWordToPdf.saveAS("F://新建 DOC 文档.doc", "F://test.pdf", SaveFormat.PDF, true, "",0, false);
} }
4、要实现上传word文件转成pdf:
一般上传文件使用的是 MultipartFile 类文件,而不是File类型,但上面的word转pdf工具方法用的是File类型的文件,因为要获取文件的路径,在此路径下重新生成一个pdf文件。
所以上传的文件是MultiparFile类型,需要转成File类型来处理
4.1、MultipartFile文件类型 转成 File 文件类型工具:( FileUtil.toFile(multiPartFile.getInputStream(), new File("xxx/xxx/xxx.doc")) )
(作用目的:就是生成一个空白的文件,然后把MultipartFile文件里的输入流内容,复制到新空白文件中) ==== MultipartFile 转 File
public class FileUtil extends org.springframework.util.FileCopyUtils {/** * 转成file * @param in InputStream * @param file File */ public static void toFile(InputStream in, final File file) { try (OutputStream out = new FileOutputStream(file)) { FileUtil.copy(in, out); } catch (IOException e) { throw Exceptions.unchecked(e); } } }
FileUtil.copy用的是框架包core:5.2.10版本的工具
4.2、MultipartFile 转成 File 后,拿到File文件的路径,就可以调用word转pdf工具生成pdf了
生成的pdf文件没有任何问题,可以正常打开:
.
标签:插件,word,watermark,doc,param,aspose,java,import,new From: https://www.cnblogs.com/spll/p/16749470.html