Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

java - how can I make a page break using itext

I want to generate a pdf using itext. I would at some point while the content was added to make a page break. I need to insert several separate conenidos dependence origin so I ask the user to do so on separate pages. Any ideas???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Anyone looking for a solution in iText7, please use the solution from @BadLeo, which is to use document.add(new AreaBreak());

Below answer is applicable for versions prior to 7.

Calling document.newPage() tells iText to place subsequent objects on a new page. The new page will only actually get created when you place the next object. Also, newPage() only creates a new page if the current page is not blank; otherwise, it's ignored; you can use setPageBlank(false) to overcome that.

Refer below link for an example: http://itextpdf.com/examples/iia.php?id=99 (Edit: dead 404)

Since the above link is dead, adding example code for anyone who is till using version prior to 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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...