简体   繁体   中英

ItextSharp MVC5 C# - text in front of existing pdf

I'm building a web app for editing PDF files using iTextSharp.

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.

Can someone explain to me how can I set a depth property for my text?

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?

Pdf does not have an explicit depth or z-axis property. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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