首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用OpenPdf插入pdf中的空白页

用OpenPdf插入pdf中的空白页
EN

Stack Overflow用户
提问于 2021-11-24 10:25:04
回答 1查看 244关注 0票数 1

嗨,我工作的简单功能,标记所有的jpg文件,并保存到pdf (与openpdf)。每一张图片都应该贴合到页面上,在它们之间我想有一个空白页。我已经有了:

代码语言:javascript
复制
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.")
  }

如何向document添加空白页

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-24 15:24:20

对于干净的解决方案,您需要使用PdfWriter实例,所以首先替换

代码语言:javascript
复制
PdfWriter.getInstance(document, new FileOutputStream(targetFile))

通过

代码语言:javascript
复制
val writer = PdfWriter.getInstance(document, new FileOutputStream(targetFile))

然后在document.add(jpg)之后添加

代码语言:javascript
复制
document.newPage()
writer.setPageEmpty(false)
document.newPage()

需要writer.setPageEmpty(false)才能使OpenPdf认为空页不是空的,因为如果它认为当前页完全为空,则会忽略document.newPage()调用。

writer.setPageEmpty(false)不同,您还可以添加一些不可见的内容,比如全白色的图像。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70094411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档