java实现word转pdf在线预览-所需jar包
java实现world转pdf所需jar包-实现pdf在线预览
一、依赖文件
二、java代码实现
package test.pdftest;
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.aspose.words.Document;
import com.aspose.words.HeaderFooter;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.HorizontalAlignment;
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.VerticalAlignment;
import com.aspose.words.WrapType;
/**
* world转pdf实现在线预览
* @author 硅谷探秘者(jia)
*
*/
public class Test {
public static void main(String[] args) {
doc2pdf("E:\\test\\files\\a.docx","E:\\test\\files\\a.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,"贾佳佳");//带水印,如果不需要直接注释掉就行了
doc.save(os, SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @Description: PDF生成水印
* @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(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("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));
}
}
二、实现效果:
fixed
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。