当前位置: 首页 > 知识库问答 >
问题:

使用iText,如何使用CssResolver和CssFile将css应用于PDF文档?

姜鹏程
2023-03-14

谢谢你的帮助。。。

在将html表格标签/片段(我已转换为字符串)转换为PDF文档时...

我能够使用此技术成功地将css样式应用于PDF文档。。。

CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(false);  
cssResolver.addCss("td {border-right: white .1px solid;}", true);

但是,我没有成功地使用现有的css文件(即,使用CssFile对象)将css应用于PDF文档,如下所示。。。

CSSResolver cssResolver = new StyleAttrCSSResolver();
InputStream csspathtest = Thread.currentThread().getContextClassLoader().getResourceAsStream("styles/itextweb.css");            
CssFile cssfiletest = XMLWorkerHelper.getCSS(csspathtest);
cssResolver.addCss(cssfiletest);             

。。。我一直无法让这个工作,不知道是什么问题。。。我正在。。。

Java.io.IOException The document has no pages

如何正确使用CssFile和CssResolver将css样式——即从现有的“. css”文件——应用到我的PDF文档?(我使用iText来完成此任务的方式有什么问题?)

(再次感谢您在这方面的帮助/指导)

下面================= 更详细的信息 ===================

Java 6、JSF(Mojarra)2.1.11、Primefaces v3.4.2、itextpdf v5.3.4、xmlworker v1.2.1

public void createPDF() throws DocumentException, CssResolverException
{
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext econtext = context.getExternalContext();

    try
    {
        String htmlstring   = context.getExternalContext().getRequestParameterMap().get("testForm:htmlstring");

        InputStream is = new ByteArrayInputStream(htmlstring.getBytes());             
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, baos);

        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);

        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        InputStream csspathtest = Thread.currentThread().getContextClassLoader().getResourceAsStream("styles/itextweb.css");            
        CssFile cssfiletest = XMLWorkerHelper.getCSS(csspathtest);
        cssResolver.addCss(cssfiletest);             

        Pipeline<?> pipeline =  new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser p = new XMLParser(worker);
        p.parse(is); //new FileInputStream("results/demo2/walden.html"));

        // step     
        document.close();

        //post back...
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");           
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-disposition","attachment;filename=file.pdf");
        response.setContentLength(baos.size());
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
        context.responseComplete();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (DocumentException e)
    {
        e.printStackTrace();
    }
}
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:p="http://primefaces.org/ui">
    <f:view contentType="text/html">
        <h:head>
            <title>test html-to-pdf with itext...</title>
            <meta charset="utf-8" />
        </h:head>
        <h:body>
            <h:form id="testForm">

                <p:panel id="queryPanel"  header="...test itext html-to-pdf conversion..." style="width:100%;">

                    <table id='table1'>
                        <thead class="dt-thd">
                            <tr id="table1-h-hdr-row">
                                <th style="width: 120px" class="dt-hhdr-c " >Last name</th>
                                <th style="width: 120px" class="dt-hhdr-c " >First Name</th>
                                <th style="width: 120px" class="dt-hhdr-c " >Middle Name</th>
                                <th style="width: 180px" class="dt-hhdr-c " >Date Of Birth</th>

                            </tr>
                        </thead>
                        <tbody>
                            <tr class="dt-r-even" onclick="uiOnRowClick('table1', 14, this)">
                                <td style="width: 120px" class="dt-c  row-selected-left" ><a class="column-link " onfocus="uiOnRowClick('table1', 14, this.parentNode.parentNode)" onclick="storeFilters()" href="#">lastnameAAA</a></td>
                                <td style="width: 120px" class="dt-c  row-selected" >firstnameAAA</td>
                                <td style="width: 120px" class="dt-c  row-selected" >A</td>
                                <td style="width: 180px" class="dt-c  row-selected" >11/27/1971</td>
                            </tr>
                            <tr class="dt-r-odd" onclick="uiOnRowClick('table1', 14, this)">
                                <td style="width: 120px" class="dt-c " ><a class="column-link " onfocus="uiOnRowClick('table1', 14, this.parentNode.parentNode)" onclick="storeFilters()" href="#">lastnameBBB</a></td>
                                <td style="width: 120px" class="dt-c " >firstnameBBB</td>
                                <td style="width: 120px" class="dt-c " >B</td>
                                <td style="width: 180px" class="dt-c " >01/15/1951</td>
                            </tr>
                            <tr class="dt-r-even" onclick="uiOnRowClick('table1', 14, this)">
                                <td style="width: 120px" class="dt-c " ><a class="column-link " onfocus="uiOnRowClick('table1', 14, this.parentNode.parentNode)" onclick="storeFilters()" href="#">lastnameCCC</a></td>
                                <td style="width: 120px" class="dt-c " >firstnameCCC</td>
                                <td style="width: 120px" class="dt-c " >C</td>
                                <td style="width: 180px" class="dt-c " >02/16/1962</td>
                            </tr>
                            <tr class="dt-r-odd" onclick="uiOnRowClick('table1', 14, this)">
                                <td style="width: 120px" class="dt-c " ><a class="column-link " onfocus="uiOnRowClick('table1', 14, this.parentNode.parentNode)" onclick="storeFilters()" href="#">lastnameDDD</a></td>
                                <td style="width: 120px" class="dt-c " >firstnameDDD</td>
                                <td style="width: 120px" class="dt-c " >D</td>
                                <td style="width: 180px" class="dt-c " >03/17/1973</td>
                            </tr>
                            <tr class="dt-r-even" onclick="uiOnRowClick('table1', 14, this)">
                                <td style="width: 120px" class="dt-c " ><a class="column-link " onfocus="uiOnRowClick('table1', 14, this.parentNode.parentNode)" onclick="storeFilters()" href="#">lastnameEEE</a></td>
                                <td style="width: 120px" class="dt-c " >firstnameEEE</td>
                                <td style="width: 120px" class="dt-c " >E</td>
                                <td style="width: 180px" class="dt-c " >04/18/1984</td>
                            </tr>
                            <tr class="dt-r-odd" onclick="uiOnRowClick('table1', 14, this)">
                                <td style="width: 120px" class="dt-c " ><a class="column-link " onfocus="uiOnRowClick('table1', 14, this.parentNode.parentNode)" onclick="storeFilters()" href="#">lastnameFFF</a></td>
                                <td style="width: 120px" class="dt-c " >firstnameFFF</td>
                                <td style="width: 120px" class="dt-c " >F</td>
                                <td style="width: 180px" class="dt-c " >05/19/1995</td>
                            </tr>
                        </tbody>
                    </table>

                    <p:commandButton
                        id="printPdf"
                        value="Print"
                        action="#{testBean.createPDF2}"
                        ajax="false"
                        onclick="printPreview(this);this.form.target='_blank'"/>

                    <h:inputHidden id="htmlstring" value="no value"/>

                </p:panel>

            </h:form>

            <h:outputStylesheet  library="styles"    name="itextweb.css"      />
            <h:outputScript      library="primefaces" name="/jquery/jquery.js" />
            <h:outputScript      library="primefaces" name="/jquery/plugins/ui/jquery-ui.custom.js" />
            <h:outputScript      library="primefaces" name="/jquery/plugins/inputmask/maskedinput.js" />
            <h:outputScript      library="js"         name="itextweb.js" />
        </h:body>
    </f:view>
</html>
function uiOnRowClick(a, b, c)
{
    alert("uiOnRowClick(a,b,c) function called...blah...");
}

function storeFilters()
{
    alert("storeFilters() function called...bleah...");
}

function printPreview(e)
{
    var t = document.getElementById("table1");
    var htmlstring = "<table id='table1-hdr' class='dt' style='width:2416px;position:absolute'>" + t.innerHTML + "</table>";
    document.getElementById('testForm:htmlstring').value = htmlstring;
}
.text1
{
    background-color: transparent !important;
    font-weight: bold;
    font-size: 2em;
    color: blue;
    text-align:center;
}

.ui-inputfield {
    background: white !important;
    height: 10px !important;
    vertical-align: middle;
    display:inline-block;
    white-space: nowrap;
}


.ui-button
{
    margin-top: .5px !important;
    vertical-align: middle !important;
    display:inline-block !important;
    white-space: nowrap !important;
    text-align: center !important;
}

.ui-message-error
{
    background: transparent !important;
    border: none !important;
    font-size: .9em !important;
    font-weight: normal !important;
    font-family: Arial, sans-serif !important;
}

.ui-message-error-icon {
    display: none;
}

.ui-messages-error
{
    background: transparent !important;
    border: none !important;
    font-size: .9em !important;
    font-weight: normal !important;
    font-family: Arial, sans-serif !important;
}

.ui-messages-error-icon {
    display: none;
}

.ui-inputfield.ui-state-error
{
    background: pink !important;
}

form *
{
box-sizing: content-box !important;
-moz-box-sizing: content-box !important;
-ms-box-sizing: content-box !important;
}


.ui-widget, .ui-widget .ui-widget
{
font-size: 90% !important;
}


.dt-thd
{

}

.table1-h-hdr-row
{

}

.dt-hhdr-c
{
    color: blue;
    background-color:  lightgray;
}

.dt-r-odd
{
    background-color: aliceblue;
}

.dt-r-even
{
    background-color:  lightskyblue;
}

.dt-c
{
    font-size: 8px;
    font-weight: normal;
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>aaa.bbb.ccc</groupId>
    <artifactId>itextweb-war</artifactId>
    <packaging>war</packaging>
    <version>1</version>
    <name>itextweb-war</name>
    <url>http://maven.apache.org</url>

    <dependencies>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.11</version>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.11</version>
        </dependency>

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>aristo</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.3.4</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>1.2.1</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
            </plugin>

        </plugins>
        <finalName>${project.name}-${project.version}</finalName>
    </build>
</project>

共有3个答案

严心水
2023-03-14

没有飞碟是出了生命周期不支持了。我们有很多麻烦与它的私人使用它的确定,但不是在一个商业案例。

马渊
2023-03-14

我认为一个更好、更强大(抽象层次更高)的工具(从XHTML生成PDF文件)将是飞碟,又名。XHTML渲染器。

它为打印介质提供了完整的CSS2支持和一些CSS3属性,您可以扩展它来呈现任何PDF(请参阅ReplacementElementFactoryAPI)。

我用它来渲染动态PDF报告(使用freemarker),带有自定义标签,如。非常简单的工具,易于理解。

请参见:http://code.google.com/p/flying-saucer/

用户指南可在此处找到:http://flyingsaucerproject.github.com/flyingsaucer/r8/guide/users-guide-R8.html

夏侯衡
2023-03-14

从您的代码开始创建一个项目,经过测试,可以很好地从带有外部CSS的html文件创建PDF文件

以下是公共存储库:https://github.com/valentin-nasta/itext-html-css-pdf-jsf-template。

 类似资料:
  • 问题内容: 尝试使用iText将越南文文档导出为PDF时遇到问题。我将越南语单词放在.xml文件中,像这样 然后让Java从xml文件中获取短语,然后使用以下方法将其转换为Unicode: 之后,将String导出为PDF-编码为UTF-8。但是程序无法显示越南语字符“ \ u1ED5”和“ \ u1EE9”。输出变为“ T chc tham gia”。能否请您告诉我如何解决此问题?谢谢 :) 问

  • 我正在尝试将HTML转换为PDF。首先,我从下面的链接将我的HTML代码转换为XHTML。http://www.cruto.com/resources/code-generators/code-converters/html-to-xhtml.asp 然后,为了测试它,我用生成的XHTML代码创建了一个HTML文件,并成功地显示在浏览器上。之后,我尝试用下面的java代码将HTML文件转换为PDF

  • 我有带表格和单元格的pdf,我在单元格中添加了带格式文本的段落,我需要阅读所有表格的列表,然后是带有css的段落中的文本(一些文本以彩色突出显示),让我知道如何从这个开始,任何我可以浏览的链接。 使用iText7 谢谢大雅

  • 我在实现中适用于简单情况,但不适用于复杂情况。原始 pdf 将显示在中央窗格中。我有一个侧窗格,其中有一些矩形,如“名称”,“签名”,“时间戳”,可以在pdf上拖动。使用 j 查询可拖动 我知道图像以像素为单位,而PDF尺寸以点为单位。因此,我将以像素为单位的图像坐标转换为点(0.75)。还考虑到,对于图像,原点是在左上 角,而在pdf中,原点是左下角,对于图像,y轴是南区,但对于pdf y轴是北

  • 我正在使用iText生成Pdf。但当我试图在pdf中添加图像时, 我mage.get实例(新的URL(timetableResource.getImageUrl()));document.add(学校标志); 但我得到的错误是 HTTP状态500-服务器为URL返回了HTTP响应代码400:http://139.59.72.150:8080/sms/attachments/23/42/school