itext实现word转pdf,添加水印倾斜铺满全屏,禁止修改和复制

来源:互联网 发布:java内存泄露场景 编辑:程序博客网 时间:2024/06/06 02:01
public class test {      static final int wdFormatPDF = 17;// PDF 格式      private static int interval = -5;       /**       * word转pdf       * @param fromAddress 待转文件地址       * @param toAddress 新文件地址       */      public static void wordToPdf(String fromAddress,String toAddress){          ActiveXComponent ax = null;          try {              long startTime = System.currentTimeMillis();              /*               * 创建不同的控件调用不同的值               * Word——Word.Application               * Excel——Excel.Application               * Powerpoint——Powerpoint.Application               * Outlook——Outlook.Application               * */              ax = new ActiveXComponent("Word.Application");              /*设置打开word文档不可见*/              ax.setProperty("Visible", false);              //获取Word文档中所有内容              Dispatch docs = ax.getProperty("Documents").toDispatch();              //打开word文档,并设置word为不可编辑和不需确认              Dispatch doc = Dispatch.call(docs,                      "Open",                       fromAddress,// FileName                      false,// ConfirmConversions                      true // ReadOnly                      ).toDispatch();                            File tofile = new File(toAddress);              if (tofile.exists()) {                  tofile.delete();              }              //word文件另存为pdf文件              Dispatch.call(doc,//                      "SaveAs", //                      toAddress, // FileName                      wdFormatPDF);              //关闭word文档              Dispatch.call(doc, "Close", false);              long endTime = System.currentTimeMillis();              System.out.println("转化完成,总共耗时" + (endTime - startTime) + "ms。");          } catch (Exception e) {              System.out.println("========Error:文档转换失败:" + e.getMessage());          } finally {              if (ax != null)                  ax.invoke("Quit", new Variant[]{});          }      }        public static void waterMark(String inputFile,              String outputFile, String waterMarkName, String password) {          try {              PdfReader reader = new PdfReader(inputFile);              PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(                      outputFile));                          byte[] ownerPassword = password.getBytes();          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_ASSEMBLY, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_DEGRADED_PRINTING, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_FILL_IN, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_CONTENTS, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_PRINTING, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_SCREENREADERS, false);          stamper.setEncryption(null, ownerPassword, PdfWriter.DO_NOT_ENCRYPT_METADATA, true);          stamper.setViewerPreferences(PdfWriter.HideToolbar|PdfWriter.HideMenubar);                      BaseFont base = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_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);            // 计算水印X,Y坐标 float x = pageRect.getWidth() / 2; float y = pageRect.getHeight() / 2;                under = stamper.getOverContent(i);                 under.saveState();                under.setGState(gs);                under.beginText();                  under.setFontAndSize(base, 15);                  // 水印文字成45度角倾斜                for (int height = interval + textH; height < pageRect.getHeight();                height = height + textH*8) {                      for (int width = interval + textW; width < pageRect.getWidth() + textW;                     width = width + textW) {                under.showTextAligned(Element.ALIGN_LEFT                , waterMarkName, width - textW,                height - textH, 45);                    }                }                // 添加水印文字                  under.endText();              }              stamper.close();          } catch (Exception e) {              e.printStackTrace();          }      }      public static void concatPDFs(List<InputStream> streamOfPDFFiles,            OutputStream outputStream, boolean paginate) {        Document document = new Document();        try {            List<InputStream> pdfs = streamOfPDFFiles;            List<PdfReader> readers = new ArrayList<PdfReader>();            int totalPages = 0;            Iterator<InputStream> iteratorPDFs = pdfs.iterator();            // Create Readers for the pdfs.            while (iteratorPDFs.hasNext()) {                InputStream pdf = iteratorPDFs.next();                PdfReader pdfReader = new PdfReader(pdf);                readers.add(pdfReader);                totalPages += pdfReader.getNumberOfPages();            }            // Create a writer for the outputstream            PdfWriter writer = PdfWriter.getInstance(document, outputStream);            document.open();            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF            // data            PdfImportedPage page;            int currentPageNumber = 0;            int pageOfCurrentReaderPDF = 0;            Iterator<PdfReader> iteratorPDFReader = readers.iterator();            // Loop through the PDF files and add to the output.            while (iteratorPDFReader.hasNext()) {                PdfReader pdfReader = iteratorPDFReader.next();                // Create a new page in the target for each source page.                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {                    document.newPage();                    pageOfCurrentReaderPDF++;                    currentPageNumber++;                    page = writer.getImportedPage(pdfReader,                            pageOfCurrentReaderPDF);                    cb.addTemplate(page, 0, 0);                    // Code for pagination.                    if (paginate) {                        cb.beginText();                        cb.setFontAndSize(bf, 9);                        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""                                + currentPageNumber + " of " + totalPages, 520,                                5, 0);                        cb.endText();                    }                }                pageOfCurrentReaderPDF = 0;            }            outputStream.flush();            document.close();            outputStream.close();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (document.isOpen())                document.close();            try {                if (outputStream != null)                    outputStream.close();            } catch (IOException ioe) {                ioe.printStackTrace();            }        }    }      public static void main(String[] args) {    try {    String to = "C:/Desktop/to.pdf";    String wordUrl = "C:/Desktop/1501139857165.doc";File file = File.createTempFile("tempFile", ".pdf");wordToPdf(wordUrl,file.getPath());waterMark(file.getPath(), to, "圣贤庸才,大人小心!!!!!!!","000000");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}    }  }
效果: