java - 使用 pdfstamper(Itext) 将页码添加到 pdf

标签 java pdf itext pdfstamper

我有这个代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try{
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=details.pdf");
        try{
        Document document = new Document(PageSize.A4, 20, 20, 130, 20);
        PdfWriter writer=PdfWriter.getInstance(document, output);
        document.open();
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        writer.setPageEvent(new HeaderAndFooter(date));
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        List arrlist = new ArrayList();
        List arrlist1 = new ArrayList();//user list
        List arrlist2 = new ArrayList();//time list
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/765a", "root", "root");
        Statement st=con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
        ResultSet rs=st.executeQuery("SELECT * FROM user_start2 where date='"+date+"' ");
         while(rs.next()){
         arrlist.add(rs.getString("data"));
         arrlist1.add(rs.getString("users"));
         arrlist2.add(rs.getString("strtime"));
         }
         for(int i=0;i<interval+1;i++){
          String str =(String) arrlist.get(i);
          String str1 ='\n'+(String) arrlist1.get(i);
          String str2 =(String) arrlist2.get(i);
          String string =str.replace("<p>","\n").replace("</p>", "\n");
          document.add(new Paragraph(str1+"("+str2+")",new com.itextpdf.text.Font(bf, 10)));
          document.add(new Paragraph(str2,new com.itextpdf.text.Font(bf, 10)));
          document.add(new Paragraph(string,new com.itextpdf.text.Font(bf, 12)));
        }
        document.close();
        response.setContentLength(output.size());
         OutputStream os = response.getOutputStream();
         output.writeTo(os);
         os.flush();
         os.close();
        con.close();
        }catch(IOException e){e.printStackTrace();}
            }catch(IOException e){e.printStackTrace();} 
        catch(DocumentException e) {}
        catch(Exception e) {    
    }
        //PDF READER
          // Create a reader  
        try{
        OutputStream out = new ByteArrayOutputStream(); 
        PdfReader reader = new PdfReader(output.toByteArray());
        PdfStamper stamper = new PdfStamper(reader, out);
        Document document = new Document(); 
        document.open();
        int n = reader.getNumberOfPages();
        PdfContentByte cbq;
        Font headerFont = new Font(FontFamily.COURIER, 13, Font.UNDERLINE);
        for (int i = 1; i <= n; i++) {
            cbq = stamper.getOverContent(i);
             ColumnText ct = new ColumnText( cbq );
             ct.setSimpleColumn( 300 , 300, 50, 50 , 150, Element.ALIGN_CENTER );
              ct.addElement( new Paragraph( "Mathias" , headerFont ) );
              ct.go();
        }
        // Close the stamper
            stamper.close();
            reader.close();
            document.close();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

我正在尝试向我的 pdf 添加页码,但上面的代码不起作用。现在作为示例,我只是添加文本 "mathias" 来检查它是否有效,但文本 “mathias” 没有出现在 pdf 页面上。其他一切正常,pdf 上的标题、文本显示但不显示来自压模的数据

我也尝试过使用这个

 for (int i = 1; i <= n; i++) {
            getHeaderTable(i, n).writeSelectedRows(0, -1, 34, 803, stamper.getOverContent(i));
        }

public static PdfPTable getHeaderTable(int x, int y) {
            PdfPTable table = new PdfPTable(2);
            table.setTotalWidth(527);
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(20);
            table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            table.addCell("FOOBAR FILMFESTIVAL");
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(String.format("Page %d of %d", x, y));
            return table;
        }

但是压模上什么也没有出现。

我错过了什么吗?

最佳答案

mkl 试图解释的内容非常简单。您正在使用以下方式将 PDF 文档发送到浏览器:

response.setContentLength(output.size());
OutputStream os = response.getOutputStream();
output.writeTo(os);

但是,此文档是加盖之前的 PDF 文档,因此如果您没有看到 PdfStamper 对文档应用任何更改,您应该不会感到惊讶。请删除这些行并查看以下代码:

//PDF READER
// Create a reader  
try{
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    PdfReader reader = new PdfReader(output.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, out);
    int n = reader.getNumberOfPages();
    PdfContentByte cbq;
    Font headerFont = new Font(FontFamily.COURIER, 13, Font.UNDERLINE);
    for (int i = 1; i <= n; i++) {
        cbq = stamper.getOverContent(i);
        ColumnText ct = new ColumnText( cbq );
        ct.setSimpleColumn( 300 , 300, 50, 50 , 150, Element.ALIGN_CENTER );
        ct.addElement( new Paragraph( "Mathias" , headerFont ) );
        ct.go();
    }
    // Close the stamper
    stamper.close();
    reader.close();
    response.setContentLength(out.size());
    OutputStream os = response.getOutputStream();
    out.writeTo(os);
} catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

请注意,我从此代码段中删除了 Document document = new Document();。请阅读the documentation 。使用 PdfStamper 时,您不需要 Document 实例。

关于java - 使用 pdfstamper(Itext) 将页码添加到 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21374006/

相关文章:

java - 有人可以帮助我在 rest-api 中使用文本文件吗?

java - 在 Android 中调用 REST Web 服务并在字符串数据中获取 null

java - 无法连接到sql server 2008实例

vba - powerpoint vba 将某些幻灯片导出为 pdf

java - 如何在 Apache FOP 中自动创建斜体/粗体字体?

java - 如何在 XPath 查询中使用 Java String 变量

java - 文档.newPage();不在 iText 中的每个循环内部工作

c# - ITextSharp 一起使用多种字体样式。即粗体、下划线、斜体...等

java - 错误 : java. lang.IllegalArgumentException:不支持额外样本

asp.net - 使用 itextSharp 创建 PDF 文件