PdfBox 2.0.0 在页面中的给定位置写入文本 [英] PdfBox 2.0.0 write text at given postion in a page

查看:58
本文介绍了PdfBox 2.0.0 在页面中的给定位置写入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从 PdfBox 1.8 过渡到 2.0.0,并且有相当显着的差异.在现有的 pdf 页面上写文本之前,我使用了 drawString.在 2.0.0 中不推荐使用绘制字符串,但 showText 在块文本中不起作用.

I have just passed from PdfBox 1.8 to 2.0.0 and there are quite significant differences. Before to write a text on an existing pdf page I used drawString. In 2.0.0 draw string is deprecated but showText does not work in a block text.

我在 1.8 中的代码:

My code in 1.8:

 contentStream.beginText()
 contentStream.moveTextPositionByAmount(250, 665)
 contentStream.drawString("1  2 3 4 5 6    7  8  9   1 0")
 contentStream.endText()

我在 2.0 中的代码

My code in 2.0

  PDDocument newPdf=null
  newPdf=PDDocument.load(sourcePdfFile)
  PDPage firstPage=newPdf.getPage(0)
  PDPageContentStream contentStream = new PDPageContentStream(newPdf, firstPage, PDPageContentStream.AppendMode.APPEND,true,true)
  contentStream.setFont(pdfFont, fontSize)
  contentStream.beginText()
  contentStream.lineTo(200,685)
  contentStream.showText("John")
  contentStream.endText()

但它不起作用...

任何人都知道我如何像 1.8 一样编写文本

Anyone has any idea about how can I write text as in 1.8

推荐答案

LineTo 是画一条线.你想要的是newLineAtOffset(moveTextPositionByAmount的弃用通知是这么说的),所以你的代码是这样的:

LineTo is to draw a line. What you want is newLineAtOffset (the deprecation notice of moveTextPositionByAmount says so), so your code is like this:

  PDDocument newPdf = PDDocument.load(sourcePdfFile);
  PDPage firstPage=newPdf.getPage(0);
  PDFont pdfFont= PDType1Font.HELVETICA_BOLD;
  int fontSize = 14;
  PDPageContentStream contentStream = new PDPageContentStream(newPdf, firstPage, PDPageContentStream.AppendMode.APPEND,true,true);
  contentStream.setFont(pdfFont, fontSize);
  contentStream.beginText();
  contentStream.newLineAtOffset(200,685);
  contentStream.showText("John");
  contentStream.endText();
  contentStream.close(); // don't forget that one!

这篇关于PdfBox 2.0.0 在页面中的给定位置写入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆