ITextRenderers html生成pdf 分页+横向
阅读原文时间:2023年07月11日阅读:2

1.pdf横向生成问题:格式化html是加上

@page{size:297mm 210mm;}

public static String formatPdfHtml(String html,String direction) {
try {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("");
htmlStr.append(""); htmlStr.append(""); htmlStr.append(""); htmlStr.append("${style_text}"); htmlStr.append(""); htmlStr.append(""); htmlStr.append("${content_text}"); htmlStr.append(""); htmlStr.append("");
StringBuilder styleStr = new StringBuilder();
StringBuilder styleBody = new StringBuilder();
styleStr.append("");

        Elements allelements = docHtml.getAllElements();  
        updateAttributes(allelements);

        Iterator<Element> styleIterator = styles.iterator();  
        while (styleIterator.hasNext()) {  
            Element element = styleIterator.next(); //将body里面的style样式【类】全部删掉  
            element.remove();  
        }

        StringBuilder cssStr = new StringBuilder();  
        Elements elements = docHtml.select("\[style\]"); //获取所有元素上的样式【属性】  
        Iterator<Element> iterator = elements.iterator();  
        while (iterator.hasNext()) {  
            cssStr.setLength(0);  
            Element element = iterator.next();  
            String style = element.attr("style");  
            if (StringUtils.isNotBlank(style)) {  
                style = StringUtils.trim(style);  
                String\[\] ss1 = StringUtils.split(style, ";");  
                for (String s : ss1) {  
                    cssStr.append(s + ";");  
                }  
                element.removeAttr("style");  
                element.attr("style", cssStr.toString());  
            }  
        }  
        docHtml.outputSettings(new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));  
        String newHtml = StringUtils.replace(htmlStr.toString(), "${content\_text}", docHtml.body().html());  
        newHtml = StringUtils.replace(newHtml, "${style\_text}", styleStr.toString());  
        newHtml = StringUtils.replace(newHtml, "&nbsp;", "");  
        return newHtml;  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
    return html;  
}

2.分页问题,生成html是在需要分页的地方加上

分页js

/**
* html生成pdf分页
* html格式化之前不能隐藏
* 如需每页都有head或者foot 将head放入 将foot放入
* 分页代码:


*/
/*var page_head = ""; //每页的头部
$(".page_head").each(function () {
page_head = $(this);
});
var page_foot = "";
$(".page_foot").each(function () {
page_foot = page_foot + $(this);
});*/

/**
* 遍历原数据表格,按高度生成新表格
* */
$(".pdf_data_table").each(function () {
var table = $(this);
var direction = $(this).attr("direction")
var page_height = ''; //每页的高度 默认500px

if (direction == '') {  
    direction = 'v';  
}  
if (page\_height == '') {  
    if (direction == 'v') {  
        page\_height = 900; //word纸张方向 竖=500 横=450  
    } else {  
        page\_height = 650; //word纸张方向 竖=500 横=450  
    }  
}  
var tbody = table.find("tbody");  
var maxIndex = tbody.find("tr").length - 1;  
var tempTable = null;  
var tempHeight = 0  
tbody.find("tr").each(function (index) {  
    var tr = $(this);  
    if (index == 0) {  
        tempTable = createDivAndTable(table);  
        tempTable.find("tbody").append(tr.clone());  
        tempHeight = tempTable.height()  
    } else {  
        /\*if (page\_head != '') {  
            tempHeight = tempHeight + page\_head.height();  
        }\*/  
        tempHeight = tempHeight + tr.height();  
        /\*if (page\_foot != '') {  
            tempHeight = tempHeight + page\_foot.height();  
        }\*/  
        if (tempHeight > page\_height) {  
            tempTable = createDivAndTable(table);  
            tempTable.find("tbody").append(tr.clone());  
            tempHeight = 0  
        } else {  
            tempTable.find("tbody").append(tr.clone());  
        }  
    }  
});  
$("#content").hide();  

});
//data_div为原来html位置
$("#data_div").remove(); //移除旧表格
$('.page_break_div:last').remove(); //删除最后一个表格分页符
// $('.page_break:last').removeAttr('style');

/**
* 生成新表格对象
* */
function createDivAndTable(table) {
//var pageDiv = $("

");
var pageDiv = $("
");
var div = $("
");
var tempTable = table.clone(); //克隆表格
var body = tempTable.find("tbody");
body.find("tr").remove(); //移除tbody中所有的tr,然后重新添加以便正确分页
/*if (page_head != '') {
pageDiv.append(page_head.clone());
}*/

pageDiv.append(tempTable);  
/\*if (page\_foot != '') {  
    pageDiv.append(page\_foot.clone());  
}\*/  
pageDiv.append(div);  
//格式话之后html的位置  
$("#data\_div\_new").append(pageDiv);  
return tempTable;  

}

demo

html(freemarker)

<#list psgzmxes as mx> <#list psTbrList as tbr> <#list psgzmxes as mx> <#list psTbrList as tbr> <#list psgzmxes as mx>
技术评分表
项目名称:${xm.name!} 项目编号:${xm.code!}
开标时间:${xm.kbdate?string('yyyy-MM-dd HH:mm')} 标包名称:${bd.bdname!}
序号 供应商名称 技术部分(${jsscoresum}分) 合计得分
${mx.pscontent}
(${mx.highestscore?string('0.00')}分)
${tbr\_index+1} ${(tbr.tbr.ztname)!} <#list zjdfList as df> <#if df.psgzmxid== mx.id && df.pbpstbrid==tbr.id> <#if df.score??>${df.score?string('0.00')} <#if (tbr.score)??>${tbr.score?string('0.00')}
${tbr\_index+1} ${(tbr.tbr.ztname)!} <#list zjdfList as df> <#if df.psgzmxid== mx.id && df.pbpstbrid==tbr.id> <#if df.score??>${df.score?string('0.00')} <#if (tbr.score)??>${tbr.score?string('0.00')}
专家签字:     ${psTbrList\[0\].psrname}(签名)

java生成代码

public static FileBean html2pdf(FileBean fileBean,String content,String watermark,String direction) throws Exception {
String fileName = PrimaryKeyUtils.genPrimaryKey();
content = HtmlUtils.formatPdfHtml(content,direction);
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = (ITextFontResolver) renderer.getSharedContext().getFontResolver();
//添加字体库 begin
// File f = new File("C:\\Windows\\Fonts");
File f = new File(SysCache.APP_PATH + "static" + File.separator + "resok" + File.separator + "Fonts");
if (f.isDirectory()) {
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
String lower = name.toLowerCase();
return lower.endsWith(".otf") || lower.endsWith(".ttf") || lower.endsWith(".ttc");
}
});
for (int i = 0; i < files.length; i++) {
fontResolver.addFont(files[i].getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
}
//添加字体库end
renderer.setDocumentFromString(content);
renderer.layout();
renderer.createPDF(os);
renderer.finishPDF();
byte[] buff = os.toByteArray();
//保存到磁盘上
//FileUtil.byte2File(buff,pdfDestPath,pdfName);

        FileUtils.writeByteArrayToFile(new File(fileBean.getPath() + fileName + ".pdf"), buff, false);  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
    if(StringUtils.isNotBlank(watermark)){  
        WatermarkUtils.addWatermark(fileBean.getPath() + fileName + ".pdf",watermark);  
    }  
    return FileSaveUtils.upLoadOther(fileBean.getPath() + fileName + ".pdf");  
}