本篇内容主要讲解“java怎么将word转为pdf并自定义水印”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java怎么将word转为pdf并自定义水印”吧!
1、依赖jar包 及 license.xml
2、代码实现:
public class Word2PdfUtil {
public static void main(String[] args) {
doc2pdf("E:\\test.doc",
"E:\\test.pdf");
}
/**
* word转pdf
*/
public static void doc2pdf(String inPath, String outPath) {
// 验证License
if (!getLicense()) {
return;
}
FileOutputStream os = null;
try {
System.out.println("开始转换...");
// 新建一个空白pdf文档
File file = new File(outPath);
os = new FileOutputStream(file);
//待转换的文件,添加水印
Document doc = new Document(inPath);
insertWatermarkText(doc, "我是水印");
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, SaveFormat.PDF);
System.out.println("转换完成...");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 验证签名
* */
private static boolean getLicense() {
boolean result = false;
try {
InputStream is = Word2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 给pdf生成水印
*/
private static void insertWatermarkText(Document doc, String watermarkText)
throws Exception {
System.out.println("开始添加水印...");
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
// 水印内容
watermark.getTextPath().setText(watermarkText);
// 水印字体
watermark.getTextPath().setFontFamily("宋体");
// 水印宽度
watermark.setWidth(500);
// 水印高度
watermark.setHeight(100);
// 旋转水印
watermark.setRotation(-40);
// 水印颜色
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("结束添加水印...");
}
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));
}
3、注:如果提示 javaSoft注册权限问题
打开注册表(regedit),找到HKEY_LOCAL_MACHINE \ SOFTWARE \ JavaSoft,右键改权限为完全许可
到此,相信大家对“java怎么将word转为pdf并自定义水印”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!