# Word增加水印
下载jar包,拷贝进入项目,单击右键选择Add as Library
创建license.xml
文件
<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>
public class WordAddWaterMarkerTest {
@Test
public void doc2pdfTest() {
// 这个加水印文字方法可用
try {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
Document document = new Document("D:\\jsyq.docx");
insertWatermarkText(document, "清源创新实验室");
//文件输出路径
document.save("D:\\jsyqwater.docx");
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean getLicense() {
boolean result = false;
try {
File file = new File("D:\\license.xml"); // 新建一个空白pdf文档
InputStream is = new FileInputStream(file); // license.xml找个路径放即可。
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 加水印方法
*
* @param doc word文件流
* @param watermarkText 水印内容
*/
public static void insertWatermarkText(Document doc, String watermarkText) {
// 居中
insertWatermarkText(doc, watermarkText, new Function<Shape, Object>() {
@Override
public Object apply(Shape 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);
return null;
}
});
// 顶部
insertWatermarkText(doc, watermarkText, new Function<Shape, Object>() {
@Override
public Object apply(Shape watermark) {
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.MARGIN);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.MARGIN);
watermark.setWrapType(WrapType.NONE);
// 我们需要自定义距离顶部的高度
watermark.setVerticalAlignment(VerticalAlignment.TOP);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
// watermark.setTop(120);
return null;
}
});
//尾部
insertWatermarkText(doc, watermarkText, new Function<Shape, Object>() {
@Override
public Object apply(Shape watermark) {
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.MARGIN);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.MARGIN);
watermark.setWrapType(WrapType.NONE);
// 我们需要自定义距离顶部的高度
watermark.setVerticalAlignment(VerticalAlignment.BOTTOM);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 设置距离顶部的高度
// watermark.setTop(480);
return null;
}
});
}
private static void insertWatermarkText(Document doc, String watermarkText,
Function<Shape, Object> watermaskPositionConfigFunc) {
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
watermark.getTextPath().setText(watermarkText);
// 这里设置为宋体可以保证在转换为PDF时中文不是乱码.
watermark.getTextPath().setFontFamily("WeiRuanYaHei");
//WeiRuanYaHei 宋体
try {
// 水印大小
watermark.setWidth(150);
watermark.setHeight(30);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 左下到右上
watermark.setRotation(-20);
//字体RGB颜色
final String colorStr = "EE8262";
watermark.getFill().setColor(new java.awt.Color(Integer.parseInt(colorStr, 16)));
watermark.setStrokeColor(new java.awt.Color(Integer.parseInt(colorStr, 16)));
watermaskPositionConfigFunc.apply(watermark);
Paragraph watermarkPara = new Paragraph(doc);
watermarkPara.appendChild(watermark);
for (Section sect : doc.getSections()) {
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
}
}
private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect,
int headerType) {
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
if (header == null) {
header = new HeaderFooter(sect.getDocument(), headerType);
sect.getHeadersFooters().add(header);
}
try {
header.appendChild(watermarkPara.deepClone(true));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
# pdf增加水印
pom.xml
添加依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.2</version>
</dependency>
private static int interval = -5;
@Test
public void testPdfW() {
waterMark("D:\\test.pdf", "D:\\testWaterMark.pdf", "水印文字");
}
public static void waterMark(String inputFile, String outputFile, String waterMarkName) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
outputFile));
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
//设置透明度
gs.setFillOpacity(0.3f);
gs.setStrokeOpacity(0.4f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());
PdfContentByte under;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 20);
//设置水印颜色
under.setColorFill(BaseColor.RED);
// 水印文字成30度角倾斜
// 你可以随心所欲的改你自己想要的角度
// 8和5可以调整水印密度
for (int height = interval + textH; height < pageRect.getHeight();
height = height + textH * 8) {
for (int width = interval + textW; width < pageRect.getWidth() + textW;
width = width + textW * 5) {
under.showTextAligned(Element.ALIGN_LEFT
, waterMarkName, width - textW,
height - textH, 30);
}
}
// 添加水印文字
under.endText();
}
//说三遍
//一定不要忘记关闭流
//一定不要忘记关闭流
//一定不要忘记关闭流
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
# Word转pdf
下载jar包,拷贝进入项目,单击右键选择Add as Library
创建license.xml
文件
<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>
@Test
public void doc2pdfTest() {
String docPath = "D:\\jsyq.docx";
String pdfPath = "D:\\jsyq.pdf";
doc2pdf(docPath, pdfPath);
}
public static boolean getLicense() {
boolean result = false;
try {
File file = new File("D:\\license.xml"); // 新建一个空白pdf文档
InputStream is = new FileInputStream(file); // license.xml找个路径放即可。
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void doc2pdf(String inPath, String outPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
long old = System.currentTimeMillis();
Document doc = new Document(inPath);
doc.save(outPath);
long now = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
}
}
# pdf转Word
下载jar包,拷贝进入项目,单击右键选择Add as Library
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>11.7.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose.pdf-11.7.0.jar</systemPath>
</dependency>
创建license.xml
文件
<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>
String licensePath = "path\\to\\license.xml";
InputStream is = new FileInputStream(licensePath);
License license = new License();
license.setLicense(is);
// 验证license是否生效,确认这个license只能适用11.7.0版本
System.out.println(Document.isLicensed());
Document document = new Document("path\\to\\test.pdf");
document.save("path\\to\\testPdf.docx", SaveFormat.DocX);
# 多个pdf文件合并
使用java代码合并PDF文件需要导入iText-2.1.7.jar包
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
public class MergeFile {
public static void main(String[] args) {
String[] files = { "e:\\1.pdf", "e:\\2.pdf", "e:\\3.pdf" };
String savepath = "e:\\temp.pdf";
mergePdfFiles(files, savepath);
}
/*
* * 合並pdf文件 * * @param files 要合並文件數組(絕對路徑如{ "e:\\1.pdf", "e:\\2.pdf" ,
* "e:\\3.pdf"}) * @param newfile
* 合並後新產生的文件絕對路徑如e:\\temp.pdf,請自己刪除用過後不再用的文件請 * @return boolean
* 產生成功返回true, 否則返回false
*/
public static boolean mergePdfFiles(String[] files, String newfile) {
boolean retValue = false;
Document document = null;
try {
document = new Document(new PdfReader(files[0]).getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
document.open();
for (int i = 0; i < files.length; i++) {
PdfReader reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
retValue = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
document.close();
}
return retValue;
}
}