如何使用iTextSharp在特定位置放置段落

Yuv*_*aj 2 c# position itext winforms

如何将文本放在pdf上的特定位置?我做了一些搜索,但没有发现任何不好的东西。我已经document.Add(new Paragraph("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(); 
    }
Run Code Online (Sandbox Code Playgroud)

Bru*_*gie 5

假设您知道如何在绝对位置添加图像(请参阅Joris的答案),但是在查看如何添加文本的情况下,问题的答案是:use ColumnText

如果只需要添加不需要换行的一行,则可以使用以下ShowTextAligned()方法:

ColumnText.showTextAligned(writer.DirectContent,
     Element.ALIGN_CENTER, new Phrase("single line"), x, y, rotation);
Run Code Online (Sandbox Code Playgroud)

在这行代码中,xy是文本中间的坐标(其他可能的对齐值是ALIGN_LEFTALIGN_RIGHT)。该rotation参数定义以度为单位的旋转。请注意,文本"single line"不会被换行。如果您要添加的文本太长,则可以通过这种方式添加“从页面上掉下来”的文本。

如果要在特定矩形内添加文本,则需要使用Rectangle对象定义列:

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();
Run Code Online (Sandbox Code Playgroud)

如果您提供的文本多于适合矩形的文本,则不会渲染该文本。但是,它仍然在ct对象中可用,因此您可以将剩余的文本添加到其他位置。

在此之前,已经询问并回答了所有这些问题:

单线:

多行:

我是否需要长时间搜索这些示例?不,我在官方网站的“文字绝对定位”下找到了它们。

那些在那里搜寻的人有智慧...