Domanda

I'm lost at the moment. What I try to accomplish is adding one PDF on another (like a watermark). The problem is that I dont seems to understand the coordinate system that is used because my watermark just behaves unexpected.

The two PDFs have different dimensions.

My target has the following dimensions:
595 height
842 width

The PDF that shall be added has this dimension:
41 height
552 width

In my code I do the following:

public bool AddPdf(ref PdfReader pdfSource, ref PdfReader pdfTarget, ref FileStream destination)
    {
        PdfStamper stamper = null;
        try
        {
            stamper = new PdfStamper( pdfSource, destination );
            PdfImportedPage importatedPage = stamper.GetImportedPage(pdfTarget, 1);

            PdfContentByte background;
            for (int iPage = 1; iPage <= pdfSource.NumberOfPages; iPage++)
            {
                background = stamper.GetOverContent(iPage);                    
                background.AddTemplate(importatedPage, 0, 0 + importHeight);
            }
        }

When I do this I would expect my watermark to appear in the bottom left. Instead it is somewhere of the page (I dont see it). Just for testing I hardcoded 600 as y position and then it is centered vertically on the page.

Can someone give me a tip please?

È stato utile?

Soluzione

So i solved the issue. The problem was that the sourcepdf had a cropbox - i only needed to correct my x and y position with that information:

            PdfStamper stamper = null;
            try
            {
            stamper = new PdfStamper(pdfSource, destination);
            PdfImportedPage importatedPage = stamper.GetImportedPage(pdfTarget, 1);
            PdfContentByte background;
            for (int iPage = 1; iPage <= pdfSource.NumberOfPages; iPage++)
            {
                background = stamper.GetOverContent(iPage);

                // here comes the important part
                Rectangle cropBox = pdfSource.GetCropBox(iPage);

                float xCorrected = 0 + cropBox.Left;
                float yCorrected = 0 + cropBox.Bottom;

                background.AddTemplate(importatedPage, xCorrected, yCorrected);
            }
        }

Take in mind that in case the pdf that you want to stamp on your original has also a cropbox, you need to reduce the x,y by x,y of that cropbox again.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top