IText 5.5.11具有编码和正确css样式的parseElements

时间:2018-03-04 17:36:57

标签: character-encoding itext

大家好我正在使用Itext 5.5.11来解析从html字符串到pdf的元素,这些元素应该用3列布局来构造。我无法编辑的这个html字符串(例如代码中的一个)。由于č,ž,ř等字符,我正在努力将编码设置为“cp1250”。提前感谢。

private Rectangle[] COLUMNS = {new Rectangle(36, 36, 200, 780),
                     new Rectangle(216, 36, 380, 780),
                     new Rectangle(396, 36, 559, 780)}; 

public byte[] generateMultiColumnPDF() {

        Document document = new Document();
        ByteArrayOutputStream pdf = new ByteArrayOutputStream();

        try {
            FontFactory.register(timesFontPath, "times");
            FontFactory.register(timesBoldFontPath, "times-bold");

            PdfWriter writer = PdfWriter.getInstance(document, pdf);
            writer.setPageEvent(this);

            document.open();        

            PdfContentByte canvas = writer.getDirectContent();
            ColumnText columnText = new ColumnText(canvas);

            int sideOfThePage = 0;
            columnText.setSimpleColumn(COLUMNS[sideOfThePage]);

            StringBuilder testHtml = new StringBuilder();
            testHtml.append("<h1>H1</h1>");
            testHtml.append("<h2>H2</h2>");
            testHtml.append("<h3>H3</h3>");
            testHtml.append("<h4>H4</h4>");
            testHtml.append("<p>testovací paragraf so speciálními znaky č ř ž </p>");

            StringBuilder cssStringBuilder = new StringBuilder();
            cssStringBuilder.append("body {font-size: 8px; font-family: times} ");
            cssStringBuilder.append("p {font-size: 8px; font-family: times; line-height: 10px} ");
            cssStringBuilder.append("h1 {font-size: 14px; font-family: times} ");
            cssStringBuilder.append("h2 {font-size: 12px; font-family: times} ");
            cssStringBuilder.append("h3 {font-size: 9px; font-family: times} ");
            cssStringBuilder.append("h4 {font-size: 8px; font-family: times} ");
            cssStringBuilder.append("li {line-height: 10px; font-family: times} ");
            cssStringBuilder.append("a {color: green} ");

            ArrayList<Element> objects = parseToElementList(testHtml.toString(), cssStringBuilder.toString());

            for (int i = 0; i < objects.size(); ++i) {
                columnText.addElement(objects.get(i));

                while (ColumnText.hasMoreText(columnText.go())) {

                    if (sideOfThePage == 0) {
                        sideOfThePage = 1;
                    } else if (sideOfThePage == 1) {
                        sideOfThePage = 2;
                    } else {
                        sideOfThePage = 0;
                        document.newPage();
                    }

                    columnText.setSimpleColumn(COLUMNS[sideOfThePage]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        document.close();
        return pdf.toByteArray();
    }

0 个答案:

没有答案