在itext中,我有一个块/短语/段落(我不介意哪个),我想在页面上的其他位置放置,例如在300 x 200.我该怎么做?
答案 0 :(得分:27)
最后我写了自己的方法来做到这一点。
private void PlaceChunck(String text, int x, int y) {
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SaveState();
cb.BeginText();
cb.MoveText(x, y);
cb.SetFontAndSize(bf, 12);
cb.ShowText(text);
cb.EndText();
cb.RestoreState();
}
答案 1 :(得分:17)
这是一个包含所有正确的套管和try / catch块的版本:
private static void absText(String text, int x, int y) {
try {
PdfContentByte cb = writer.getDirectContent();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.saveState();
cb.beginText();
cb.moveText(x, y);
cb.setFontAndSize(bf, 12);
cb.showText(text);
cb.endText();
cb.restoreState();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:2)
我在这些方面做了一些事情,也许它会帮助别人:
ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(left,bottom,right,top);
ct.setText(new Phrase("String"));
ct.go();
答案 3 :(得分:0)
在我的情况下,只有这个解决方案运行良好。
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(FILE));
添加方法
private void addTextData(Document document, String text) {
PdfContentByte cb = pdfWriter.getDirectContent();
cb.beginText();
try {
BaseFont f_cn = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.setFontAndSize(f_cn, 40);
float requiredX = 50;
float requiredY = 50;
Paint paint = new Paint();
paint.setTextSize(40);
Typeface typeface=Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
paint.setTypeface(typeface);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
Rect result = new Rect();
paint.getTextBounds(text, 0, text.length(), result);
Log.i("Text dimensions", "Width: "+result.width()+"-Height: "+result.height());
float calculatedY = document.getPageSize().getHeight() - result.height() - requiredY;
cb.setTextMatrix(requiredX, calculatedY);
cb.showText(text);
cb.endText();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
这对您有帮助。
答案 4 :(得分:0)
希望这对您有所帮助! 这是我的代码...
DatabaseError
添加功能:
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
FixText("Add Your Text",400,700,writer,14);
document.close();