使用Flying Saucer在PDF标题后的巨大空白区域

时间:2017-12-16 12:14:07

标签: java html itext flying-saucer pdf-extraction

我正在尝试使用Flying Saucer将HTML页面导出为PDF。由于某种原因,页面在标题(id =“divTemplateHeaderPage1”)之后有一个很大的空格。 我的HTML代码的jsFiddle链接正由PDF渲染器使用:https://jsfiddle.net/Sparks245/uhxqdta6/

下面是用于呈现PDF的Java代码(Test.html与小提琴中的HTML代码相同)并且只呈现一页。

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.HTTP;
import org.json.JSONException;
import org.json.*;
import org.json.simple.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import org.json.simple.parser.*;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;
import com.lowagie.text.List;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;


@WebServlet("/PLPDFExport")
public class PLPDFExport extends HttpServlet 
{

    //Option for Serialization
    private static final long serialVersionUID = 1L;

    public PLPDFExport() 
    {
        super();
    }

    //Get method
    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) 
                   throws ServletException, 
                          IOException 
    {

    }

    //Post method
    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response) 
                   throws ServletException, 
                          IOException
    {
            StringBuffer jb = new StringBuffer();
            String line = null;
            int Pages; 
            String[] newArray = null;

            try 
            {
                BufferedReader reader = request.getReader();
                while ((line = reader.readLine()) != null)
                {   jb.append(line);
                }
            } catch (Exception e) { /*report an error*/ }


            try 
            {
                JSONObject obj = new JSONObject(jb.toString());

                Pages = obj.getInt("Pages");

                newArray = new String[1];  
                for(int cnt = 1; cnt <= 1; cnt++)
                {  

                    StringBuffer  buf = new StringBuffer();

                    String base = "C:/Users/Sparks/Desktop/";

                    buf.append(readFile(base + "Test.html"));

                    newArray[0] = buf.toString(); 
                }
            } 


            catch (JSONException e)
            {
                // crash and burn
                throw new IOException("Error parsing JSON request string");
            }


            //Get the parameters

            OutputStream os = null;
            try {

                final File outputFile = File.createTempFile("FlyingSacuer.PDFRenderToMultiplePages", ".pdf");
                os = new FileOutputStream(outputFile);

                ITextRenderer renderer = new ITextRenderer();


                // we need to create the target PDF
                // we'll create one page per input string, but we call layout for the first

                renderer.setScaleToFit(true);
                renderer.isScaleToFit();
                renderer.setDocumentFromString(newArray[0]);

                renderer.layout();
                try {
                    renderer.createPDF(os, false);
                } catch (DocumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // each page after the first we add using layout() followed by writeNextDocument()
                for (int i = 1; i < newArray.length; i++) {
                    renderer.setScaleToFit(true);
                    renderer.isScaleToFit();
                    renderer.setDocumentFromString(newArray[i]);
                    renderer.layout();
                    try {
                        renderer.writeNextDocument();
                    } catch (DocumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                // complete the PDF
                renderer.finishPDF();

                System.out.println("PDF Downloaded to " + outputFile );
                System.out.println(newArray[0]);

            }
            finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) { /*ignore*/ }
                }
            }

            //Return
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("File Uploaded");
    }

    String readFile(String fileName) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            return sb.toString();
        } finally {
            br.close();
        }
    }

}

导出PDF的链接:https://drive.google.com/file/d/13CmlJK0ZDLolt7C3yLN2k4uJqV3TX-4B/view?usp=sharing

我尝试添加像page-break-inside这样的css属性:避免使用标题分区,但它不起作用。此外,我尝试将绝对位置和顶部边距添加到标题div正下方的正文分区(id =“divTemplateBodyPage1”),但白色空间仍然存在。

任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:0)

请查看PDF的元数据:

enter image description here

您使用的是iText Group 未认可的旧第三方工具,它使用了iText 2.1.7,这是一个可追溯到2009年的that should no longer be used版iText。

抱怨并写&#34;我的代码大约7年前没有工作&#34; 可能没问题,但是如果您将使用最新版本的iText,将HTML转换为PDF的结果如下所示:

enter image description here

我只需要一行代码即可获得此结果:

HtmlConverter.convertToPdf(new File(src), new File(dest));

在此行src是源HTML的路径,dest是生成的PDF的路径。

我只需对您的HTML应用一个小的更改。我改变了@page这样的属性:

@page {
  size: 27cm 38cm;
  margin: 0.2cm;
}

如果我没有更改CSS的这一部分,页面大小将是A4,在这种情况下,并非所有内容都适合页面。我还添加了一小部分,因为我不喜欢边框贴在页面两侧的事实。

士气:不要使用旧版本的库! Download the latest version of iText and the pdfHTML add-on。您需要iText 7 corepdfHTML add-on。您可能还想阅读HTML to PDF tutorial