java后台生成pdf文件

已经实践两种方法,第一种用doc模板 生成的时候替换模板中需要替换的内容,再讲替换好的doc转换成pdf。

第二种生成html页面将页面转pdf,这种更直观,所见即所得。

第一种需要定制模板,然后生成pdf下载打印。因为模板有可能随时改动,样式内容都可以发生变化。所以我这边在用doc做模板,先将变量替换进去,生成新的doc 再讲新的doc转换为pdf让用户下载。随时可以修改模板 ,不要需要修改代码,导出的pdf就会自动跟着改动。

doc替换文字用的网上找的别人的方法。

用模板和数据替换生成新的doc

   public void toWord(String infilePath, String outfilePath, Map<String, Object> map) {
        File intfile = new File(infilePath);
        FileInputStream fileInputStream = null;
        File outfile = new File(outfilePath);
        FileOutputStream out;
        try {
            fileInputStream = new FileInputStream(intfile);
            template = new WordTemplate(fileInputStream);

            template.replaceTag(map);// 鏇挎崲瀛楃涓叉ā鐗�

            out = new FileOutputStream(outfile);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

 下面的代码是替换的代码,需要poi-3.16.jar,poi-ooxml-3.15.jar,poi-ooxml-schemas-3.15.jar,poi-scratchpad-3.16.jar,poi-tl-0.0.3.jar,注意下版本,我在这里踩了坑 有的版本会影响到原有处理excel的功能 ,有的会导致pdf 没法导出。


import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

public class WordTemplate {

    private XWPFDocument document;

    public WordTemplate(InputStream inputStream) throws IOException {
        document = new XWPFDocument(inputStream);
    }

    public void replaceTag(Map<String, Object> map) {
        for (Entry<String, Object> item : map.entrySet()) {
            if (item.getKey().equals("String")) {// 鐩爣涓烘枃鏈�
                Map<String, String> tempMap = (Map<String, String>) item.getValue();
                replaceParagraphs(tempMap);
                replaceTables(tempMap);
            } else if (item.getKey().equals("Table")) {// 鐩爣涓鸿〃鏍�
                replaceKeyToTables((Map<String, Object>) item.getValue());
            }

        }

    }

    public void write(OutputStream outputStream) throws IOException {
        document.write(outputStream);
    }

    /**
     * 鏇挎崲娈佃惤閲岀殑淇℃伅顒�
     * 
     * @param map
     */
    private void replaceParagraphs(Map<String, String> map) {
        List<XWPFParagraph> allXWPFParagraphs = document.getParagraphs();
        for (XWPFParagraph XwpfParagrapg : allXWPFParagraphs) {
            XWPFParagraphHandler XwpfParagrapgUtils = new XWPFParagraphHandler(XwpfParagrapg);
            XwpfParagrapgUtils.replaceAll(map);
        }
    }

    /**
     * 鏇挎崲琛ㄦ牸閲岀殑淇℃伅顒�
     * 
     * @param map
     */
    private void replaceTables(Map<String, String> map) {
        List<XWPFTable> xwpfTables = document.getTables();
        for (XWPFTable xwpfTable : xwpfTables) {
            XWPFTableHandler xwpfTableUtils = new XWPFTableHandler(xwpfTable);
            xwpfTableUtils.replace(map);
        }
    }

    /**
     * 鏇挎崲琛ㄦ牸
     *
     * @author huangdongkui
     * @param map
     */
    public void replaceKeyToTables(Map<String, Object> param) {
        List<XWPFParagraph> paragraphList = document.getParagraphs();
        if (paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                String text = paragraph.getParagraphText();
                for (Entry<String, Object> entry : param.entrySet()) {
                    String key = entry.getKey();
                    if (text.indexOf(key) != -1) {

                        Object value = entry.getValue();
                        if (value instanceof List) {// 琛ㄦ牸
                            text = text.replace(key, "");

                            XWPFTable tableOne = document.insertNewTbl(paragraph.getCTP().newCursor());

                            //娣诲姞鍒�
                            for (int col = 1; col < ((Map<String, String>) ((List) value).get(0)).entrySet().size(); col++) {
                                tableOne.addNewCol();
                            }

                            // 濉厖鍒楀ご
                            XWPFTableRow crow = tableOne.createRow();
                            int k = 0;
                            for (Entry<String, String> col : ((Map<String, String>) ((List) value).get(0)).entrySet()) {
                                String skey = col.getKey();
                                if (skey!=null&&!skey.equals("")) {
                                    crow.getCell(k).setText(skey);

                                    k++;
                                }
                            }

                            for (int i = 1; i < ((List) value).size(); i++) {
                                // 娣诲姞琛�
                                XWPFTableRow rrow = tableOne.createRow();
                                int j = 0;
                                for (Entry<String, String> col : ((Map<String, String>) ((List) value).get(i)).entrySet()) {
                                    String sValue = col.getValue();
                                    if (sValue!=null&&!sValue.equals(""))  {
                                        rrow.getCell(j).setText(sValue);

                                        j++;
                                    }
                                }

                            }

                            tableOne.removeRow(0);
                            setTableWidthAndHAlign(tableOne, "8000", STJc.CENTER);

                        }
                        List<XWPFRun> runs = paragraph.getRuns();

                        for (XWPFRun xwpfrun : runs) {
                            xwpfrun.setText("", 0);
                        }

                    }
                }

            }
        }
    }

    public void setTableWidthAndHAlign(XWPFTable table, String width, STJc.Enum enumValue) {
        CTTblPr tblPr = getTableCTTblPr(table);
        CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
        if (enumValue != null) {
            CTJc cTJc = tblPr.addNewJc();
            cTJc.setVal(enumValue);
        }

        tblWidth.setW(new BigInteger(width));
        tblWidth.setType(STTblWidth.DXA);

    }

    /**
     * @Description: 寰楀埌Table鐨凜TTblPr,涓嶅瓨鍦ㄥ垯鏂板缓
     */
    public CTTblPr getTableCTTblPr(XWPFTable table) {
        CTTbl ttbl = table.getCTTbl();
        CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
        return tblPr;
    }

}

生成doc没有问题之后 转换pdf   ,用到jar 有org.apache.poi.xwpf.converter.core-1.0.4.jar,org.apache.poi.xwpf.converter.pdf-1.0.4.jar

         template = "c:/合同模板/"+categoryCode+".docx";
        WordTemplateUtilities.GetInstance().toWord(template, outfilePath, map);
            String pdfPath = filePath + UUID.randomUUID() + ".pdf";
            WordTemplateUtilities.GetInstance().convertWordToPdf(outfilePath, pdfPath);
            return pdfPath;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class WordTemplateUtilities {
   
	public static void convertWordToPdf(String wordPath, String pdfPath) throws IOException {

		FileInputStream inpuFile = new FileInputStream(wordPath);
		File outFile=new File(pdfPath);		
	    //从输入的文件流创建对象
	    XWPFDocument document = new XWPFDocument(inpuFile);
	    //创建PDF选项
	    PdfOptions pdfOptions = PdfOptions.create();//.fontEncoding("windows-1250")
	    //为输出文件创建目录
	    outFile.getParentFile().mkdirs();
	    //执行PDF转化
	    PdfConverter.getInstance().convert(document, new FileOutputStream(outFile), pdfOptions);	    
	    System.out.println("成功转换:"+pdfPath);

	}
}

 

第二种 过两天在写

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过以下步骤实现: 1. 在后台接收到pdf二进制流文件后,将其保存为byte[]数组。 2. 将byte[]数组转换为InputStream对象。 3. 使用PdfBox库(或其他pdf处理库)将InputStream对象转换为PDF文档对象(PDDocument)。 4. 根据需要,对PDF文档进行修改(例如添加水印、修改内容等)。 5. 将修改后的PDF文档保存到本地文件系统。 下面是一个简单的Java代码示例,演示如何将接收到的pdf二进制流文件保存到本地: ```java import org.apache.pdfbox.pdmodel.PDDocument; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class PdfFileHandler { public void savePdf(byte[] pdfBytes, String savePath) throws IOException { // 将byte[]数组转换为InputStream对象 InputStream inputStream = new ByteArrayInputStream(pdfBytes); // 使用PdfBox库将InputStream对象转换为PDDocument对象 PDDocument document = PDDocument.load(inputStream); // 将PDDocument对象保存为本地文件 document.save(new File(savePath)); // 关闭PDDocument对象 document.close(); } public static void main(String[] args) throws IOException { byte[] pdfBytes = // 从请求中获取pdf二进制流文件 String savePath = "C:/temp/test.pdf"; // 保存路径 PdfFileHandler handler = new PdfFileHandler(); handler.savePdf(pdfBytes, savePath); } } ``` 请注意,本示例仅演示了最基本的保存操作。在实际使用中,您可能需要根据具体的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值