java实现word转pdf无水印,水印自定义
在网上也是找了好久才找到的一些比较好的资料,我自己整理了一下,方便后面的各位小伙伴使用。
先上效果图
所需的包百度网盘:
https://pan.baidu.com/s/1uzB9ZglDplv1Uu4S_fpKcA
提取码:lxbm
这里还有有excel的包,有没有很开心啊,当然我还有excel转pdf的博客,不用你到处找啦。如果对你有用点个赞!欧耶
直接上源码
import com.aspose.words.Shape; import com.aspose.words.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WordToPdfUtils { private static Logger logger = LoggerFactory.getLogger(WordToPdfUtils.class); public static void main(String[] args) { doc2pdf("D:\\直播问题Q&A.docx","D:\\word.pdf"); } public static void doc2pdf(String inPath, String outPath) { FileOutputStream os =null; try { File file = new File(outPath); // 新建一个空白pdf文档 os = new FileOutputStream(file); Document doc = new Document(inPath); // Address是将要被转化的word文档 //添加水印 insertWatermarkText(doc,"某某科技有限公司"); //保存pdf文件 doc.save(os, SaveFormat.PDF); } catch (Exception e) { e.printStackTrace(); }finally{ if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * * @Title: insertWatermarkText * @Description: PDF生成水印 * @author mzl * @param doc * @param watermarkText * @throws Exception * @throws */ private static void insertWatermarkText(Document doc, String watermarkText) throws Exception { Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT); //水印内容 watermark.getTextPath().setText(watermarkText); //水印字体 watermark.getTextPath().setFontFamily("宋体"); //水印宽度 watermark.setWidth(400); //水印高度 watermark.setHeight(100); //旋转水印 watermark.setRotation(-30); //水印颜色 watermark.getFill().setColor(Color.lightGray); watermark.setStrokeColor(Color.lightGray); watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); watermark.setWrapType(WrapType.NONE); watermark.setVerticalAlignment(VerticalAlignment.CENTER); watermark.setHorizontalAlignment(HorizontalAlignment.CENTER); Paragraph watermarkPara = new Paragraph(doc); watermarkPara.appendChild(watermark); for (Section sect : doc.getSections()) { insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY); insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST); insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN); } System.out.println("Watermark Set"); } private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception { HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType); if (header == null) { header = new HeaderFooter(sect.getDocument(), headerType); sect.getHeadersFooters().add(header); } header.appendChild(watermarkPara.deepClone(true)); } }