2

Hi I working on simple function which marge all jpg files and save them to pdf (with openpdf). Each image should be fitted to page, and between them I want to have one blank page. I already have:

def createFromImage(directory: String, targetFile: String): Unit = {
    logger.info(s"Create pdf from images in $directory.")
    val document = new Document()
    PdfWriter.getInstance(document, new FileOutputStream(targetFile))
    document.open()
    val resultFiles = new File(directory).listFiles().toList.map(_.getAbsolutePath)
    resultFiles.filter(x => x.contains(".jpg")).map {
      file =>
        import com.lowagie.text.Image
        val jpg: Image = Image.getInstance(file)
        document.setPageSize(PageSize.A4)
        val ratio: Float = PageSize.A4.getWidth / jpg.getWidth
        jpg.scalePercent(ratio * 100)
        document.add(jpg)
    }
    document.close()
    logger.info("Pdf created.")
  }

How to add blank page to document?

1 Answer 1

2

For a clean solution you need to use the PdfWriter instance, so first replace

PdfWriter.getInstance(document, new FileOutputStream(targetFile))

by

val writer = PdfWriter.getInstance(document, new FileOutputStream(targetFile))

Then add after document.add(jpg):

document.newPage()
writer.setPageEmpty(false)
document.newPage()

The writer.setPageEmpty(false) is needed to make OpenPdf think the empty page is not empty because it ignores document.newPage() calls if it thinks the current page is completely empty.

Instead of writer.setPageEmpty(false) you can alternatively add some invisible content like an all-white image.

1
  • 1
    Thanks, it works :)
    – Kuba Wenta
    Commented Nov 24, 2021 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.