精华内容
下载资源
问答
  • itextword转pdf
    千次阅读
    2019-01-21 16:42:16

    第一步。maven   pom文件引入

    		<dependency>
    			<groupId>fr.opensagres.xdocreport</groupId>
    			<artifactId>fr.opensagres.poi.xwpf.converter.pdf</artifactId>
    			<version>2.0.1</version>
    			<exclusions>
    				<exclusion>
    					<artifactId>2.1.7</artifactId>
    					<groupId>fr.opensagres.xdocreport.itext</groupId>
    				</exclusion>
    			</exclusions>
    		</dependency>

          注意:需要排除itext-2.1.7.jar,重新在项目中引入附件中的itext-2.1.7.jar

          jar地址,https://download.csdn.net/download/weixin_43770790/10930491

    第二布。创建测试类

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    
    import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
    import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
    
    public class test {
    	
    	public static void main(String[] args) throws Exception {
    		FileInputStream input = new FileInputStream("C:\\Users\\yang\\Desktop\\ceshi.docx");
    		OutputStream out = new FileOutputStream("C:\\Users\\yang\\Desktop\\ceshi.pdf");
    
    		XWPFDocument doc = new XWPFDocument(input);
    
    		PdfOptions options = PdfOptions.create();
    		
    		PdfConverter.getInstance().convert(doc, out, options);
    
    	}
    
    }

             "C:\\Users\\yang\\Desktop\\ceshi.docx" 为测试用word文档。

             "C:\\Users\\yang\\Desktop\\ceshi.pdf"   为生成的pdf文件。

            修改路径直接运行即可。

     

    关于Linux系统下字体问题,可以百度“Linux安装windows字体”,网上有很多教程。

    参考:https://bbs.csdn.net/topics/380075439

    更多相关内容
  • Itext word转pdf

    热门讨论 2012-01-18 15:09:23
    文档POI只支持往生成的中填入文本,对于图片根本就不支持。使用itext 生成rtf格式的直接保存为word
  • word转换成pdf确实有很多种方案!最近正好需要做一个这样的功能,需求是将word模板进行签名后转换为pdf。...这里记录一下最终的方案:利用poi+itextpdf进行word转pdf。此资源按包含源码和maven依赖。
  • java 利用利用poi+itextpdf进行word转pdf,里面有源码和依赖还有效果图,无需安装插件,感觉是一种比较好的方法
  • java实现word转pdf

    2021-11-25 09:52:08
    java实现word转pdf 效果及使用教程可以参考 https://blog.csdn.net/u012775558/article/details/121530527
  • itext word怎么pdf

    千次阅读 2020-03-17 18:11:33
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Microsoft Word 2007+", "docx"); chooser.setFileFilter(filter); chooser.setMultiSelectionEnabled(true); int returnVal = chooser....
    import java.io.File;
     import java.io.FileInputStream;
     import java.io.FileOutputStream;
     import java.util.Iterator;
     import java.util.List;
     import javax.swing.JFileChooser;
     import javax.swing.filechooser.FileNameExtensionFilter;
     import org.apache.poi.xwpf.usermodel.XWPFDocument;
     import org.apache.poi.xwpf.usermodel.XWPFParagraph;
     import org.apache.poi.xwpf.usermodel.XWPFPicture;
     import org.apache.poi.xwpf.usermodel.XWPFPictureData;
     import org.apache.poi.xwpf.usermodel.XWPFRun;
     import com.itextpdf.text.Chunk;
     import com.itextpdf.text.BaseColor;
     import com.itextpdf.text.Document;
     import com.itextpdf.text.Font;
     import com.itextpdf.text.FontFactory;
     import com.itextpdf.text.Image;
     import com.itextpdf.text.pdf.PdfWriter;
     import com.itextpdf.text.PageSize;
    
     public class WordToPdfConverter{
     public static void main(String[] args){
       selectFiles();
     }
     public static void selectFiles(){
      JFileChooser chooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter("Microsoft Word 2007+", "docx");
      chooser.setFileFilter(filter);
      chooser.setMultiSelectionEnabled(true);
      int returnVal = chooser.showOpenDialog(null);
      if(returnVal == JFileChooser.APPROVE_OPTION) {
       File[] Files=chooser.getSelectedFiles();
       System.out.println("Please wait...");
                for( int i=0;i<Files.length;i++){     
                 String wordfile=Files[i].toString();            
                 convertWordToPdf(wordfile,wordfile.substring(0,wordfile.indexOf('.'))+".pdf");
                 }
       System.out.println("Conversion complete");
              }
     }
     public static void convertWordToPdf(String src, String desc){
      try{
      //create file inputstream object to read data from file 
      FileInputStream fs=new FileInputStream(src);
      //create document object to wrap the file inputstream object
      XWPFDocument doc=new XWPFDocument(fs); 
      //72 units=1 inch
      Document pdfdoc=new Document(PageSize.A4,72,72,72,72);
      //create a pdf writer object to write text to mypdf.pdf file
      PdfWriter pwriter=PdfWriter.getInstance(pdfdoc, new FileOutputStream(desc));
      //specify the vertical space between the lines of text
      pwriter.setInitialLeading(20);
      //get all paragraphs from word docx
      List<XWPFParagraph> plist=doc.getParagraphs();
      
      //open pdf document for writing
      pdfdoc.open();
      for (int i = 0; i < plist.size(); i++) {
       //read through the list of paragraphs
       XWPFParagraph pa = plist.get(i);
       //get all run objects from each paragraph
           List<XWPFRun> runs = pa.getRuns();
           //read through the run objects
           for (int j = 0; j < runs.size(); j++) {       
            XWPFRun run=runs.get(j);
            //get pictures from the run and add them to the pdf document
            List<XWPFPicture> piclist=run.getEmbeddedPictures();
            //traverse through the list and write each image to a file
            Iterator<XWPFPicture> iterator=piclist.iterator();
            while(iterator.hasNext()){
               XWPFPicture pic=iterator.next();
               XWPFPictureData picdata=pic.getPictureData();
               byte[] bytepic=picdata.getData(); 
               Image imag=Image.getInstance(bytepic);
              pdfdoc.add(imag);
                  
            }
            //get color code
            int color=getCode(run.getColor());
            //construct font object
            Font f=null;
            if(run.isBold() && run.isItalic())
             f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.BOLDITALIC, new BaseColor(color));
               else if(run.isBold())
             f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.BOLD, new BaseColor(color));
            else if(run.isItalic())
             f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.ITALIC, new BaseColor(color));
            else if(run.isStrike())
             f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.STRIKETHRU, new BaseColor(color));
            else
             f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.NORMAL, new BaseColor(color));
            //construct unicode string
            String text=run.getText(-1);
            byte[] bs;
            if (text!=null){
             bs=text.getBytes();
             String str=new String(bs,"UTF-8");
             //add string to the pdf document
             Chunk chObj1=new Chunk(str,f);
             pdfdoc.add(chObj1);
            }      
            
           }
           //output new line
           pdfdoc.add(new Chunk(Chunk.NEWLINE));
           }
          //close pdf document  
      pdfdoc.close();
      }catch(Exception e){e.printStackTrace();}
     } 
     public static int getCode(String code){
      int colorCode;
      if(code!=null)
       colorCode=Long.decode("0x"+code).intValue();
      else
       colorCode=Long.decode("0x000000").intValue();
      return colorCode;
     }
    
     }
    展开全文
  • java 实现word 转PDF (采用第三方技术 IText、Poi、Jsoup)iText-2.0.8.jar core-renderer.jar iTextAsian.jar iTextAsianCmaps.jar jsoup-1.8.1.jar
  • 如图,这是itextword转pdf 代码如下: ``` XWPFDocument doc = new XWPFDocument(new FileInputStream(file)); // 以下几行代码是把这个word文件转化成pdf文件 File pdfFile = getPdfFile(FILE_TYPE_PDF); ...
  • 求大神给我发送用itextword 转pdf的java程序代码!
  • SpringBoot项目,使用poi、itextpdf将excel、ppt、word文件转为pdf,并对pdf文件进行签章;对Excel文件加图片水印,并加密设置为只读。下面的方法都是返回的byte数组,可视具体情况直接将文件输出。office文件分为...

    1 环境及背景

    SpringBoot项目,使用poi、itextpdf将excel、ppt、word文件转为pdf,并对pdf文件进行签章;
    对Excel文件加图片水印,并加密设置为只读。
    下面的方法都是返回的byte数组,可视具体情况直接将文件输出。
    office文件分为2003跟2007版本,所以处理的方法回有所区别。
    还有很多其他方式可以实现转pdf,例如可以用第三方插件aspose处理office文件,但是需要收费;
    可以使用spire,也是收费的;
    还可以使用OpenOffice办公组件,加org.jodconverter,组件是适用于Linux,windows的。

    2 pdf文件加盖签章

    数字证书生成:

    keytool -storepass 123456 -genkeypair -keyalg RSA -keysize 1024 -sigalg SHA1withRSA -validity 3650 -alias mycert -keystore my.keystore -dname "CN=www.sample.com, OU=sample, O=sample, L=BJ, ST=BJ, C=CN"
    

    打开cmd窗口直接执行上面命令即可,会生成一个 my.keystore的文件。

    /**
         * 对pdf进行签章
         * @param src pdf文件输入流
         * @param imgPath 签章图片路径
         * @param reason 签章原因
         * @param location 签章地点
         * @return
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static byte[] sign(InputStream src,String imgPath,String reason,String location) throws GeneralSecurityException, IOException, DocumentException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] resBytes = null;
            try{
                //读取keystore ,获得私钥和证书链
                KeyStore keyStore = KeyStore.getInstance("JKS");
                keyStore.load(ConvertImgToBase64Util.loadImgResource("templates/keystore/keystore.p12"),"123456".toCharArray());
                String alias = (String)keyStore.aliases().nextElement();
                PrivateKey PrivateKey = (PrivateKey) keyStore.getKey(alias, "123456".toCharArray());
                Certificate[] chain = keyStore.getCertificateChain(alias);
    
                PdfReader pdfReader = new PdfReader(src);
                Rectangle  rectangle= pdfReader.getPageSize(1);
                float urx =  rectangle.getRight()-100;
                float ury = rectangle.getTop()-100;
                float llx = urx-200;
                float lly = ury-200;
                PdfStamper stamper = PdfStamper.createSignature(pdfReader, baos, '', null, false);
                // 获取数字签章属性对象,设定数字签章的属性
                PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
                appearance.setReason(reason);
                appearance.setLocation(location);
                appearance.setVisibleSignature(new Rectangle(llx,lly,urx,ury), 1, "sign");
                //获取盖章图片
                byte[] imgBytes = ConvertImgToBase64Util.image2Bytes(imgPath);
                Image image = Image.getInstance(imgBytes);
                appearance.setSignatureGraphic(image);
                //设置认证等级
                appearance.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
                //印章的渲染方式,这里选择只显示印章
                appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                ExternalDigest digest = new BouncyCastleDigest();
                //签名算法,参数依次为:证书秘钥、摘要算法名称,例如MD5 | SHA-1 | SHA-2.... 以及 提供者
                ExternalSignature signature = new PrivateKeySignature(PrivateKey, DigestAlgorithms.SHA1, null);
                //调用itext签名方法完成pdf签章
                MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0,MakeSignature.CryptoStandard.CMS);
                resBytes = baos.toByteArray();
            }catch (Exception e){
                log.error("pdf文件签章异常:{}",e);
            }finally {
                try{
                    if(baos != null){
                        baos.close();
                    }
                }catch (IOException e){
                    log.error("关闭io流异常:{}",e);
                }
            }
            return resBytes;
        }
    

    上面代码出现的keystore.p12就是my.keystore

    3 word转pdf

    3.1 docx转pdf

    public static byte[] docxToPdf(InputStream src) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] resBytes = null;
            String result;
            try {
                // pdf文件的尺寸
                Document pdfDocument = new Document(PageSize.A3, 72, 72, 72, 72);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, baos);
                XWPFDocument doc = new XWPFDocument(src);
                pdfWriter.setInitialLeading(20);
                java.util.List<XWPFParagraph> plist = doc.getParagraphs();
                pdfWriter.open();
                pdfDocument.open();
                for (int i = 0; i < plist.size(); i++) {
                    XWPFParagraph pa = plist.get(i);
                    java.util.List<XWPFRun> runs = pa.getRuns();
                    for (int j = 0; j < runs.size(); j++) {
                        XWPFRun run = runs.get(j);
                        java.util.List<XWPFPicture> piclist = run.getEmbeddedPictures();
                        Iterator<XWPFPicture> iterator = piclist.iterator();
                        while (iterator.hasNext()) {
                            XWPFPicture pic = iterator.next();
                            XWPFPictureData picdata = pic.getPictureData();
                            byte[] bytepic = picdata.getData();
                            Image imag = Image.getInstance(bytepic);
                            pdfDocument.add(imag);
                        }
                        // 中文字体的解决
                        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                        Font font = new Font(bf, 11.0f, Font.NORMAL, BaseColor.BLACK);
                        String text = run.getText(-1);
                        byte[] bs;
                        if (text != null) {
                            bs = text.getBytes();
                            String str = new String(bs);
                            Chunk chObj1 = new Chunk(str, font);
                            pdfDocument.add(chObj1);
                        }
                    }
                    pdfDocument.add(new Chunk(Chunk.NEWLINE));
                }
                //需要关闭,不然无法获取到输出流
                pdfDocument.close();
                pdfWriter.close();
                resBytes = baos.toByteArray();
            } catch (Exception e) {
                log.error("docx转pdf文件异常:{}",e);
            }finally {
                try{
                    if(baos != null){
                        baos.close();
                    }
                }catch (IOException e){
                    log.error("docx转pdf关闭io流异常:{}",e);
                }
            }
            return resBytes;
        }
    

    3.2 doc转pdf

    /**
         * doc转为pdf,先将doc转为html,再将html转为pdf,因为使用poi无法直接将doc转为pdf
         * @param src
         * @return
         */
        public static  byte[]  doc2pdf(InputStream src){
            byte[]  res = null;
            try{
                String html = OfficeToPdfUtil.doc2Html(src);
                html = OfficeToPdfUtil.formatHtml(html);
                res = OfficeToPdfUtil.htmlToPdf(html);
            }catch (Exception e){
                log.error("doc转pdf异常:{}",e);
            }
            return res;
        }
    
    
    public class OfficeToPdfUtil {
        /**
         * html转为pdf
         * @param html
         * @return
         */
        public static byte[] htmlToPdf(String html) {
            com.itextpdf.text.Document document = null;
            ByteArrayInputStream bais = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] resBytes = null;
            try {
                document = new com.itextpdf.text.Document(PageSize.A4);
                PdfWriter writer = PdfWriter.getInstance(document, baos);
                document.open();
                bais = new ByteArrayInputStream(html.getBytes());
                XMLWorkerHelper.getInstance().parseXHtml(writer, document, bais,
                        Charset.forName("UTF-8"), new FontProvider() {
                            @Override
                            public boolean isRegistered(String s) {
                                return false;
                            }
    
                            @Override
                            public Font getFont(String s, String s1, boolean embedded, float size, int style, BaseColor baseColor) {
                                // 配置字体
                                Font font = null;
                                try {
                                    BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                                    font = new Font(bf, size, style, baseColor);
                                    font.setColor(baseColor);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                return font;
                            }
                        });
                document.close();
                writer.close();
                resBytes = baos.toByteArray();
            } catch (Exception e) {
                log.error("html转pdf异常:{}",e);
            } finally {
                if (document != null) {
                    document.close();
                }
                if (bais != null) {
                    try {
                        bais.close();
                    } catch (IOException e) {
                        log.error("html转pdf关闭io流异常:{}",e);
                    }
                }
            }
            return resBytes;
        }
    
        /**
         * doc文件转为html
         * @param inputStream
         * @return
         */
        public static String doc2Html(InputStream inputStream) {
            String content = null;
            ByteArrayOutputStream baos = null;
            try {
                HWPFDocument wordDocument = new HWPFDocument(inputStream);
                WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
                wordToHtmlConverter.setPicturesManager(new PicturesManager() {
                    @Override
                    public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                        return null;
                    }
                });
                wordToHtmlConverter.processDocument(wordDocument);
                org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
                DOMSource domSource = new DOMSource(htmlDocument);
                baos = new ByteArrayOutputStream();
                StreamResult streamResult = new StreamResult(baos);
    
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer serializer = tf.newTransformer();
                serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
                serializer.setOutputProperty(OutputKeys.INDENT, "yes");
                serializer.setOutputProperty(OutputKeys.METHOD, "html");
                serializer.transform(domSource, streamResult);
            } catch (Exception e) {
                log.error("doc转html异常:{}",e);
            } finally {
                try {
                    if (baos != null) {
                        content = new String(baos.toByteArray(), "utf-8");
                        baos.close();
                    }
                } catch (Exception e) {
                    log.error("doc转html关闭io流异常:{}",e);
                }
            }
            return content;
        }
    
        /**
         * 使用jsoup规范化html
         * @param html html内容
         * @return 规范化后的html
         */
        public static String formatHtml(String html) {
            org.jsoup.nodes.Document doc = Jsoup.parse(html);
            // 去除过大的宽度
            String style = doc.attr("style");
            if (StringUtils.isNotEmpty(style) && style.contains("width")) {
                doc.attr("style", "");
            }
            Elements divs = doc.select("div");
            for (org.jsoup.nodes.Element div : divs) {
                String divStyle = div.attr("style");
                if (StringUtils.isNotEmpty(divStyle) && divStyle.contains("width")) {
                    div.attr("style", "");
                }
            }
            // jsoup生成闭合标签
            doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
            doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
            return doc.html();
        }
    
    }
    

    4 ppt转pdf

    4.1 pptx转pdf

    public static byte[] pptxToPdf(InputStream src) {
            Document document = null;
            XMLSlideShow slideShow = null;
            FileOutputStream fileOutputStream = null;
            PdfWriter pdfWriter = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] resBytes = null;
            try {
                //使用输入流pptx文件
                slideShow = new XMLSlideShow(src);
                //获取幻灯片的尺寸
                Dimension dimension = slideShow.getPageSize();
                //创建一个写内容的容器
                document = new Document(PageSize.A3, 72, 72, 72, 72);
                //使用输出流写入
                pdfWriter = PdfWriter.getInstance(document, baos);
                //使用之前必须打开
                document.open();
                pdfWriter.open();
                PdfPTable pdfPTable = new PdfPTable(1);
                //获取幻灯片
                java.util.List<XSLFSlide> slideList = slideShow.getSlides();
                for (int i = 0, row = slideList.size(); i < row; i++) {
                    //获取每一页幻灯片
                    XSLFSlide slide = slideList.get(i);
                    for (XSLFShape shape : slide.getShapes()) {
                        //判断是否是文本
                        if(shape instanceof XSLFTextShape){
                            // 设置字体, 解决中文乱码
                            XSLFTextShape textShape = (XSLFTextShape) shape;
                            for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                                for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
                                    textRun.setFontFamily("宋体");
                                }
                            }
                        }
                    }
                    //根据幻灯片尺寸创建图形对象
                    BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics2d = bufferedImage.createGraphics();
                    graphics2d.setPaint(Color.white);
                    graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
                    //把内容写入图形对象
                    slide.draw(graphics2d);
                    graphics2d.dispose();
                    //封装到Image对象中
                    Image image = Image.getInstance(bufferedImage, null);
                    image.scalePercent(50f);
                    // 写入单元格
                    pdfPTable.addCell(new PdfPCell(image, true));
                    document.add(image);
                }
                document.close();
                pdfWriter.close();
                resBytes = baos.toByteArray();
            } catch (Exception e) {
                log.error("pptx转pdf异常:{}",e);
            } finally {
                try {
                    if (baos != null) {
                         baos.close();
                    }
                } catch (IOException e) {
                    log.error("pptx转pdf关闭io流异常:{}",e);
                }
            }
            return resBytes;
        }
    

    4.2 ppt转pdf

    /**
         * 将ppt转为pdf,兼容ppt和pptx
         * @param is
         * @return
         */
        public static byte[] ppt2pdf(InputStream is) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] resBytes = null;
            try {
                Document pdfDocument = new Document();
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, baos);
                HSLFSlideShow hslfSlideShow = new HSLFSlideShow(is);
                double zoom = 2;
                if (hslfSlideShow == null) {
                    XMLSlideShow ppt = new XMLSlideShow(is);
                    if (ppt == null) {
                        throw new NullPointerException("获取ppt文件数据失败");
                    }
                    Dimension pgsize = ppt.getPageSize();
                    List<XSLFSlide> slide = ppt.getSlides();
                    AffineTransform at = new AffineTransform();
                    at.setToScale(zoom, zoom);
                    pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
                    pdfWriter.open();
                    pdfDocument.open();
                    PdfPTable table = new PdfPTable(1);
                    for (XSLFSlide xslfSlide : slide) {
                        BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
                        Graphics2D graphics = img.createGraphics();
                        graphics.setTransform(at);
    
                        graphics.setPaint(Color.white);
                        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                        xslfSlide.draw(graphics);
                        graphics.getPaint();
                        Image slideImage = Image.getInstance(img, null);
                        table.addCell(new PdfPCell(slideImage, true));
                    }
                    ppt.close();
                    pdfDocument.add(table);
                    pdfDocument.close();
                    pdfWriter.close();
                    resBytes = baos.toByteArray();
                    return resBytes;
                }
                Dimension pgsize = hslfSlideShow.getPageSize();
                List<HSLFSlide> slides = hslfSlideShow.getSlides();
                pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
                pdfWriter.open();
                pdfDocument.open();
                AffineTransform at = new AffineTransform();
                PdfPTable table = new PdfPTable(1);
                for (HSLFSlide hslfSlide : slides) {
                    BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics = img.createGraphics();
                    graphics.setTransform(at);
    
                    graphics.setPaint(Color.white);
                    graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                    hslfSlide.draw(graphics);
                    graphics.getPaint();
                    Image slideImage = Image.getInstance(img, null);
                    table.addCell(new PdfPCell(slideImage, true));
                }
                hslfSlideShow.close();
                pdfDocument.add(table);
                pdfDocument.close();
                pdfWriter.close();
                resBytes = baos.toByteArray();
                return resBytes;
            } catch (Exception e) {
                log.error("ppt转为pdf异常:{}",e);
            }
            return resBytes;
        }
    

    这里兼容有点问题,当HSLFSlideShow hslfSlideShow = new HSLFSlideShow(is)无法创建对象时,io流无法再被使用了,则无法再去创建XMLSlideShow对象。但是可以使用此方法转ppt后缀的文件。

    5 excel文件加图片水印,并加密

    @Slf4j
    public class ExcelWaterMakerUtils {
    
        /**
         * 给Excel添加图片水印,并加密,返回新文件的byte数组
         * @param imgPath
         * @param fileName
         * @param fis
         * @return
         */
        public static byte[] addWaterMaker(String imgPath,String fileName, InputStream fis){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedImage bufferImg = null;
            byte[] resBytes = null;
            try {
                Workbook workbook;
                if (fileName.endsWith(".xlsx")){
                    workbook = new XSSFWorkbook(fis);
                } else {
                    workbook = new HSSFWorkbook(fis);
                }
                //设置Excel为只读
                String password = RandomStringUtils.random(6,false,true);
                int sheetNumbers = workbook.getNumberOfSheets();
                short rightNum = 3;
                short leftNum = 2;
                for (int i = 0; i < sheetNumbers; i++) {
                    Sheet sheet =  workbook.getSheetAt(i);
                    sheet.protectSheet(password);
                    Row row = sheet.getRow(1);
                    if(row == null){
                        break;
                    }
                    short cellLastNum = row.getLastCellNum();
                    rightNum = (short) (cellLastNum-1);
                    leftNum = (short) (cellLastNum - 2);
                    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                    InputStream img = ConvertImgToBase64Util.loadImgResource(imgPath);
                    bufferImg = ImageIO.read(img);
                    //第二个参数将会决定插入图片形式,如果是一个png的图片,背景透明,但是此处设置为jpg格式将会自动添加黑色背景
                    ImageIO.write(bufferImg, "png", byteArrayOut);
                    //画图的顶级管理器,一个sheet只能获取一个
                    Drawing drawing = sheet.createDrawingPatriarch();
                    //anchor主要用于设置图片的属性
                    ClientAnchor anchor = drawing.createAnchor(0, 0, 255, 255,leftNum, 1, rightNum, 1);
    //            anchor.setAnchorType(2);
                    //插入图片
                    drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
                    Picture pic = drawing.createPicture(anchor,
                            workbook.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG));
                    pic.resize();
                }
                workbook.write(baos);
                resBytes = baos.toByteArray();
                fis.close();
                baos.close();
            } catch (Exception e) {
                log.error("Excel盖章异常:{}",e);
            }finally{
                try{
                    if(fis != null){
                        fis.close();
                    }
                    if(baos != null){
                        baos.close();
                    }
                }catch (IOException ioe){
                    log.error("Excel盖章关闭io流异常:{}",ioe);
                }
            }
            return resBytes;
        }
    }
    

    图片的位置是根据excel表的行列来定位的,所以不同的excel文件图片的大小可能会有变化,需要优化下,我优化了很久没能实现,将就用着吧。。。
    原本是将excel转成pdf文件,加盖受控签章的,但是复杂的exce转成pdf后,样式变化太大,乱了。

    展开全文
  • C#将WORD转换为PDF的Demo

    2015-09-16 18:20:49
    VS2010写的将Word转换成PDF的例子,例子页面为About.aspx,服务器需要安装Office2010
  • public class test { static final int wdFormatPDF = 17;// PDF 格式 private static int interval = -5; /** * word转pdf * @param fromAddress 待文件地址 * @param toAddress
    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 block
    			e.printStackTrace();
    		}
        }  
    }
    
    
    
    
    效果:
    
    
    
    
     
    
    展开全文
  • 这一篇提供上一篇修改过的的源代码。...采用其它方式生成pdf的,也可以在自己项目中找找有没有类似的类,可以借鉴修改。 修改后的类 /* * $Id: DefaultSplitCharacter.java 3427 2008-05-24 18:3...
  • c#word转pdf

    2018-09-14 11:07:53
    将已经存在的word的文件,转换为pdf,之前用过Aspose.Words,但是保存为pdf时乱码,就找到了这个,按照文件里的说明填写,就可以成功,图片一定要看,不然报错,dll最好自己下载,上nuget就能找到,下载安装,就可以...
  • 首先,要使用itext,先导入其相关联的jar包,如下: <!--项目要使用iText,必须引入jar包。才能使用,maven依赖如下:--> <dependency> ...com.itextpdf<...itextpdf</artifactId> ...
  • 关于java中实现word转pdf

    千次阅读 2021-10-12 14:38:43
    1.java中实现word转pdf几种方式如下 1.使用jacob(Java COM Bridge)操作offfice的方式,基于这种方式无论是水印还是格式都可以完美转换;但是这个方式都只是基于windos下,但有些项目是需要部署到linux下的,因此这...
  • Java通过IText导出wordpdf所有jar

    热门讨论 2015-01-16 14:35:06
    Java通过IText导出wordpdf所有jar(包括spring相关jar,是我工程中所有的jar包)
  • word转pdf所需jar

    2021-08-24 15:13:15
    1.0.6.jar、org.apache.poi.xwpf.converter.pdf-1.0.6.jar、pdfbox-2.0.13.jar、poi-ooxml-schemas-3.15.jar、poi-ooxml-3.15.jar、xmpbox-2.0.13.jar、fr.opensagres.xdocreport.itext.extension-1.0.6.jar
  • 使用IText生成PDFWORD文档

    热门讨论 2013-06-18 08:09:06
    使用IText生成PDFWORD文档 包括源码和IText所需jar包
  • java中word转pdf遇到的中文字体问题

    千次阅读 2019-08-24 21:59:28
    记一次将word文档转为PDF文档中遇到的Maven依赖问题,在网上查找解决方案时选择了。 <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>org.apache.poi.xwpf....
  • 样把pdf转换成wordPDF是一种文件格式,全称是Portable Document Format,这种文件格式的最大优点是与操作系统平台无关,可以完美再现原稿的设计风貌。也就是说一个pdf文档,无论是在windows、 Unix还是Mac OS操作...
  • java实现word文件转pdf功能

    千次阅读 2021-08-06 16:10:18
    项目需要使用java将后台生成的word文件转化为pdf,第一次做这个所以找了很多资料和代码,但一直都有问题。 有的可以转化但在第一页有水印:Evaluation Warning: The document was created with Spire.Doc for JAVA. ...
  • 生成pdf文件的方法有很多,网上也有很多的介绍,本文主要主要是讲生成pdf乱码的问题,而且还十分诡异,具体生成pdf的步骤同学们可以自己百度,也可以参考如下链接: https://www.cnblogs.com/LUA123/p/5108007.html...
  • Java实现PDF生成(Word文档转Pdf

    千次阅读 2022-01-14 15:43:09
    1, 准备模板,模板为Word 文档,当修改好想要的格式后,保存为Pdf格式。 2,准备软件(Adobe Acrobat 9 Pro), 需要编辑PDF,如哪里需要添加文字,哪里需要添加图片 软件部分 1.点击表单,启动表单向导 - 现有文档...
  • com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> import java.io.FileOutputStream; import ...
  • EasyPoi导出word文档,itextpdf转换pdf 文章目录EasyPoi导出word文档,itextpdf转换pdf前言一、依赖二、工具类1.WordUtil2.PDF工具类3.测试注意: 前言 一、依赖 <!--pdf--> <dependency> &...
  • Java通过IText导出wordpdf

    万次阅读 热门讨论 2014-06-25 15:49:37
    最近做的项目中需要用到导出wordpdf的功能(还有图表),在网上找了
  • 接到一个java后台实现excel转pdf的需求,多方辗转查阅文档后,最终用iText7的pdfoffice拓展模块实现了最完美的效果,记录如下。pom引入依赖包,由于pdfoffice是收费模块,官方未发布到maven中心仓库,我把自己下载的...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,137
精华内容 1,254
热门标签
关键字:

itextword转pdf