C# 如何使用iTextSharp在特定位置放置段落
如何将文本放置在pdf的特定位置?我做了一点搜索,但没有找到太好的东西。我有C# 如何使用iTextSharp在特定位置放置段落,c#,winforms,position,itext,C#,Winforms,Position,Itext,如何将文本放置在pdf的特定位置?我做了一点搜索,但没有找到太好的东西。我有document.Add(新段落(“Date:+DateTime.Now”)
document.Add(新段落(“Date:+DateTime.Now”)我想把它放在pdf文件的一个特定区域
我的代码:
private void savePDF_Click(object sender, EventArgs e)
{
FileStream fileStream = new FileStream(nameTxtB.Text + "Repair.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Document document = new Document();
document.Open();
iTextSharp.text.Rectangle rectangle = new iTextSharp.text.Rectangle(PageSize.LETTER);
PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream);
iTextSharp.text.Image r3tsLogo = iTextSharp.text.Image.GetInstance("rt3slogo.PNG"); //creates r3ts logo
iTextSharp.text.Image r3Info = iTextSharp.text.Image.GetInstance("R3 Information.PNG"); //creates r3 information text below r3ts logo
r3tsLogo.SetAbsolutePosition(document.PageSize.Width - 375 - 0f, document.PageSize.Height - 130 - 0f);
r3Info.SetAbsolutePosition(document.PageSize.Width - 365 - 0f, document.PageSize.Height - 170 - 0f); //higher the number in height the lower the place of text on paper
//less number will result in text more to right in width
//increase size of picture
r3tsLogo.ScalePercent(120);
r3Info.ScalePercent(65);
//---------------adds all images to pdf file ---------------------------------
document.Add(r3tsLogo);
document.Add(r3Info);
document.Add(new Paragraph("Date:" + DateTime.Now));
document.Close();
}
这一概念在《iText in action》一书中有详细解释。可以在网站上找到
简短代码示例(请查看网站上的其他示例):
假设您知道如何在绝对位置添加图像(请参见Joris的答案),但看看如何添加文本,那么您的问题的答案是:使用ColumnText
如果只需要添加不需要包装的单行,可以使用ShowTextAligned()
方法:
ColumnText.showTextAligned(writer.DirectContent,
Element.ALIGN_CENTER, new Phrase("single line"), x, y, rotation);
在这行代码中,x
和y
是文本中间的坐标(其他可能的对齐值是ALIGN\u LEFT
和ALIGN\u RIGHT
)。旋转
参数定义以度为单位的旋转。请注意,文本“单行”
不会被包装。如果要添加的文本太长,可以通过这种方式添加“从页面上掉下来”的文本
如果要在特定矩形内添加文本,则需要使用矩形
对象定义列:
ColumnText ct = new ColumnText(writer.DirectContent);
ct.setSimpleColumn(new Rectangle(0, 0, 523, 50));
ct.addElement(new Paragraph("This could be a very long sentence that needs to be wrapped"));
ct.go();
如果提供的文本多于矩形,则不会呈现该文本。但是,它仍将在ct
对象中可用,以便您可以在其他位置添加剩余的文本
所有这些问题之前都有人问过并回答过:
单行:
多行:
我是否需要长时间搜索这些示例?没有,我在官方网站上找到的
对于那些搜索的人来说,智慧是存在的。我认为问题不在于如何定位图像,而在于如何将日期:“+DateTime.Now”
定位在绝对位置。当然:这也是一个以前已经回答过很多次的问题。如何更改这一列中的字体text.showTextAligned(writer.DirectContent,Element.ALIGN_CENTER,新短语(“单行”),x,y,rotation)?
ColumnText ct = new ColumnText(writer.DirectContent);
ct.setSimpleColumn(new Rectangle(0, 0, 523, 50));
ct.addElement(new Paragraph("This could be a very long sentence that needs to be wrapped"));
ct.go();