java通过aspose实现word转pdf,加水印

这段代码展示了如何使用Aspose库将Word文档转换为PDF,并在PDF上添加水印。首先,引入Aspose和iText依赖,然后通过Aspose将Word转为PDF,接着在PDF的header中插入水印,最后使用iText添加水印图像。整个过程包括了文件操作、Aspose组件授权验证以及水印设置等步骤。
摘要由CSDN通过智能技术生成

引入jar

	<!-- word转pdf-->
	<dependency>
			<groupId>com.aspose.words</groupId>
			<artifactId>aspose-words</artifactId>
			<version>21.11.0-jdk17</version>
		</dependency>
		<!-- 加水印-->
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext</artifactId>
			<version>4.2.0</version>
		</dependency>

代码

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.aspose.words.Document;
import com.aspose.words.HeaderFooter;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.Node;
import com.aspose.words.Paragraph;
import com.aspose.words.Section;
import com.aspose.words.Shape;
import com.aspose.words.ShapeType;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

/**
 *
 * @Title: WordToPdfUtils
 * aspose 收费
 * @Description:
 */

public class WordToPdfUtils {

	/**
	 * word to pdf ---com.aspose.words
	 *
	 * @param inPath 原始word 全路径
	 * @param outPath 生成的pdf 全路径
	 * @param  outPdfAndWaterMarkPath 带水印的pdf全路径
	 * @param waterMarkImagePath 水印图片的全路径
	 * @author an
	 * @throws Exception
	 */
	public static String docPdf(String inPath, String outPath,
								String outPdfAndWaterMarkPath, String waterMarkImagePath) {
		FileOutputStream fileOS = null;
		FileOutputStream fileOS2 = null;
		// 1 验证aspose.word组件是否授权
		if (!isWordLicense()) {
			return null;
		}
		// 2 word转pdf
		try {
			Document doc = new Document(inPath);// 原始word路径
			fileOS = new FileOutputStream(new File(outPath));// 输出路径
			doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
//			fileOS.close();
			System.out.println("word转pdf--ok");
			// 3设置pdf的header,否则加水印报错
			Node watermark = new Shape(doc, ShapeType.IMAGE);
			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");

			// 4添加水印
			fileOS2 = new FileOutputStream(new File(outPdfAndWaterMarkPath));
			BufferedOutputStream bos = new BufferedOutputStream(fileOS2);
			PdfReader reader = new PdfReader(outPath);
			PdfStamper stamper = new PdfStamper(reader, bos);
			int total = reader.getNumberOfPages() + 1;
			PdfContentByte content;
			PdfGState gs = new PdfGState();
			for (int i = 1; i < total; i++) {
				// content = stamper.getOverContent(i);// 在内容上方加水印
				content = stamper.getUnderContent(i);// 在内容下方加水印
				gs.setFillOpacity(0.2f);// 水印透明度
				content.setGState(gs);
				Image image = Image.getInstance(waterMarkImagePath);
				/*
				 * img.setAlignment(Image.LEFT | Image.TEXTWRAP);
				 * img.setBorder(Image.BOX); img.setBorderWidth(10);
				 * img.setBorderColor(BaseColor.WHITE);
				 * img.scaleToFit(100072);//大小 img.setRotationDegrees(-30);//旋转
				 */
				image.setAbsolutePosition(200, 206); // set the first background
				// image of the absolute
				image.scaleToFit(200, 200);
				content.addImage(image);
				System.out.println("Watermark--ok");
			}
			stamper.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("word转pdf失败");
		}finally{
			if(fileOS !=null){
				try {
					closeStream(fileOS);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fileOS2 !=null){
				try {
					closeStream(fileOS2);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// EPUB, XPS, SWF 相互转换
		return outPdfAndWaterMarkPath;
	}

	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));
	}

	/**
	 * @Description: 验证aspose.word组件是否授权:无授权的文件有水印和试用标记
	 */
	public static boolean isWordLicense() {
		boolean result = false;
		try {
			
			// 避免文件遗漏
			String licensexml = "<License>\n"
					+ "<Data>\n"
					+ "<Products>\n"
					+ "<Product>Aspose.Total for Java</Product>\n"
					+ "<Product>Aspose.Words for Java</Product>\n"
					+ "</Products>\n"
					+ "<EditionType>Enterprise</EditionType>\n"
					+ "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
					+ "<LicenseExpiry>20991231</LicenseExpiry>\n"
					// +
					// "<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n"
					+ "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n"
					+ "</Data>\n"
					+ "<Signature>\n"
					+ "sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n"
					+ "</License>";
			InputStream inputStream = new ByteArrayInputStream(
					licensexml.getBytes());
			com.aspose.words.License license = new com.aspose.words.License();
			license.setLicense(inputStream);
			closeStream(inputStream);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(" 验证aspose.word组件是否授权失败");
		}
		return result;
	}

	private static void closeStream(OutputStream outputStream)
			throws IOException {
		if (outputStream != null) {
			outputStream.close();
		}
	}

	private static void closeStream(InputStream inputStream) throws IOException {
		if (inputStream != null) {
			inputStream.close();
		}
	}

	public static void main(String[] args) throws IOException {
		
		try {

			String inPath = "D:/app/通知.docx";
			
			String outPath = "D:/app/文件_1.pdf";
			String outPdfAndWaterMarkPath = "D:/app/文件_2.pdf";
			String waterMarkPath = "D:/app/logo.jpg";
			docPdf(inPath, outPath, outPdfAndWaterMarkPath, waterMarkPath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值