欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

openoffice将word转成pdf及添加水印

程序员文章站 2022-07-10 20:22:44
...

系统维护需求,需要将word转成pdf,上一篇博客是把word2003的模板升级成word2007模板,因为旧模板生成的word为xml格式转成pdf后内容不对,在网上搜寻了很久linux系统相关支持,发现了openoffice4.
参考:openoffice安装和卸载
https://blog.csdn.net/lx_nhs/article/details/99305227
https://blog.csdn.net/zhou920786312/article/details/79964040
启动openoffice
linux下:

cd /opt/openoffice4/program 

 ./soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard &

查看是否启动
ps -ef | grep openoffice
贴上部分java代码word转成pdf

 public  boolean officeToPDF(String sourceFile, String destFile) {
		        try {

		            File inputFile = new File(sourceFile);
		           // Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(inputFile), "UTF-8")); 
		            
		            if (!inputFile.exists()) {
		                // 找不到源文件, 则返回false
		                return false;
		            }
		            // 如果目标路径不存在, 则新建该路径
		            File outputFile = new File(destFile);
		            if (!outputFile.getParentFile().exists()) {
		                outputFile.getParentFile().mkdirs();
		            }
		            //如果目标文件存在,则删除
		            if (outputFile.exists()) {
		                outputFile.delete();
		            }
		            
		            
/*		            Document document = new Document();
		            document.loadFromFile("Sample.docx");
		            //保存结果文件
		            document.saveToFile("out/toPDF.pdf", FileFormat.PDF);*/
		            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
		            connection.connect();
		            //用于测试openOffice连接时间
		            System.out.println("连接时间:" + df.format(new Date()));
		            //DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
		            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

		            converter.convert(inputFile, outputFile);
		            //测试word转PDF的转换时间
		            System.out.println("转换时间:" + df.format(new Date()));
		            connection.disconnect();
		            return true;
		        } catch (Exception e) {
		            e.printStackTrace();
		            System.err.println("openOffice连接失败!请检查IP,端口");
		        } 
		        return false;
		    }

iText相关添加图片或者文字水印功能

 public static void setWatermark(BufferedOutputStream bos, String input, String waterMarkName, int permission)
     throws DocumentException, IOException {
			 PdfReader reader = new PdfReader(input);
			 PdfStamper stamper = new PdfStamper(reader, bos);
			 int total = reader.getNumberOfPages() + 1;
			 PdfContentByte content;
			 BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			 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);
			     content.beginText();
			     content.setColorFill(Color.LIGHT_GRAY);
			     content.setFontAndSize(base, 50);
			     content.setTextMatrix(70, 200);
			    // content.showTextAligned(Element.ALIGN_CENTER, "公司内部文件,请注意保密!", 300, 350, 55);
			     Image image = Image.getInstance(ProjectEnv.getWebappPath()+"/0001.jpg");
			     /*
			       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(0, 0); // set the first background
			                                             // image of the absolute
			     image.scaleToFit(850, 850);
			     content.addImage(image);
			     content.setColorFill(Color.BLACK);
			   //  content.setFontAndSize(baase, 8);
			    // content.showTextAligned(Element.ALIGN_CENTER, "下载时间:" + waterMarkName + "", 300, 10, 0);
			     content.endText();
			
			 }
			 stamper.close();
		}

再贴一段代码,pdf拼接用

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) {
            System.out.println(e);
        } finally {
            System.out.println("合并执行结束");
            document.close();
        }
        return retValue;
    }