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
?
CodePudding user response:
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.