简体   繁体   English

ItextSharp MVC5 C#-现有pdf前面的文本

[英]ItextSharp MVC5 C# - text in front of existing pdf

I'm building a web app for editing PDF files using iTextSharp. 我正在构建一个Web应用程序,用于使用iTextSharp编辑PDF文件。

When I try to write to the PDF, the text is getting printed behind an existing content, however I need to print it on top of it. 当我尝试写入PDF时,文本被打印在现有内容的后面,但是我需要在其顶部打印。

Can someone explain to me how can I set a depth property for my text? 有人可以向我解释如何为文本设置depth属性吗?

This is my code 这是我的代码

using (var reader = new PdfReader(oldFile))
{
    using (var fileStream = new FileStream(newFile, FileMode.Create, FileAccess.Write))
    {
        var document = new Document(reader.GetPageSizeWithRotation(1));
        var writer = PdfWriter.GetInstance(document, fileStream);

        document.Open();

        try
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            try
            {
                cb.SetFontAndSize(BaseFont.CreateFont(), 12);
                cb.SetTextMatrix(10, 100);
                cb.ShowText("Customer Name");
            }
            finally
            {
                cb.EndText();
            }

            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            cb.AddTemplate(page, 0, 0);

        }
        finally
        {
            document.Close();
            writer.Close();
            reader.Close();
        }
    }
}

pdf看起来像这样,桌子后面是一个字

Can someone explain to me how can I set a depth property for my text? 有人可以向我解释如何为文本设置depth属性吗?

Pdf does not have an explicit depth or z-axis property. Pdf没有明确的深度或z轴属性。 What is drawn first, therefore, is covered by what is drawn later. 因此,先绘制的内容将包含在随后绘制的内容中。

So if you want to have the template under your added text, you should pull the code adding the template before the code adding the text: 因此,如果要在添加的文本下放置模板,则应在添加文本的代码之前拉入添加模板的代码:

PdfContentByte cb = writer.DirectContent;

PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);

cb.BeginText();
try
{
    cb.SetFontAndSize(BaseFont.CreateFont(), 12);
    cb.SetTextMatrix(10, 100);
    cb.ShowText("Customer Name");
}
finally
{
    cb.EndText();
}

Alternatively you can make use of am itextsharp feature: it actually created two content streams, the direct content and the under content, and puts the under content before the direct content. 或者,您可以使用amextextrrp功能:它实际上创建了两个内容流,直接内容和底层内容,并将底层内容放在直接内容之前。

Thus, if rearranging the code as above is not an option for you, you can instead add the background to the under content instead of the direct content. 因此,如果您不希望按照上述方法重新排列代码,则可以将背景添加到底层内容中,而不是直接内容中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM