【问题标题】:how can I make a page break using itext如何使用 itext 进行分页
【发布时间】:2013-06-16 09:45:27
【问题描述】:

我想使用 itext 生成一个 pdf。我会在某些时候添加内容以进行分页。我需要插入几个单独的 conenidos 依赖源,所以我要求用户在单独的页面上这样做。有什么想法???

【问题讨论】:

    标签: java itext


    【解决方案1】:

    任何在iText7中寻找解决方案的人,请使用@BadLeo的解决方案,即使用document.add(new AreaBreak());

    以下答案适用于 7 之前的版本。

    调用document.newPage() 告诉iText 将后续对象放置在新页面上。只有在您放置下一个对象时,才会真正创建新页面。此外,newPage() 仅在当前页面不为空白时创建新页面;否则,它被忽略;你可以使用setPageBlank(false) 来解决这个问题。

    请参阅以下链接以获取示例: http://itextpdf.com/examples/iia.php?id=99(编辑:死 404)

    由于上述链接已失效,请为使用 iText7 之前版本的任何人添加示例代码。

    /**
     * Creates from the given Collection of images an pdf file.
     *
     * @param result
     *            the output stream from the pdf file where the images shell be written.
     * @param images
     *            the BufferedImage collection to be written in the pdf file.
     * @throws DocumentException
     *             is thrown if an error occurs when trying to get an instance of {@link PdfWriter}.
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static void createPdf(final OutputStream result, final List<BufferedImage> images)
      throws DocumentException, IOException
    {
      final Document document = new Document();
      PdfWriter.getInstance(document, result);
      for (final BufferedImage image : images)
      {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        final Image img = Image.getInstance(baos.toByteArray());
        document.setPageSize(img);
        document.setPageBlank(false);
        document.newPage();
        img.setAbsolutePosition(0, 0);
        document.add(img);
      }
      document.close();
    }
    

    【讨论】:

    • 添加页面后,您需要为新页面创建一个新的PDPageContentStream,以便将内容放到正确的位置......
    • 为什么要用死链接而不是粘贴一些代码?
    【解决方案2】:

    对于 iText7 试试:

    document.add(new AreaBreak());
    

    来源:http://itextsupport.com/apidocs/itext7/7.0.0/com/itextpdf/layout/element/AreaBreak.html

    【讨论】:

    • 这实际上就像一个魅力。调用 document.newPage() 只会添加一个新的空白页面,但任何应该附加在新页面上的新对象仍会附加在第一页上。对象在第一页上相互重叠,而其他对象是空白的。
    • @andre_northwind 你需要创建一个新内容 = new PDPageContentStream(doc, page);为新页面。
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2012-11-10
    • 1970-01-01
    • 2011-06-17
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多