简体   繁体   English

如何使用 itextsharp 更改 PDF 中的背景图像颜色

[英]How can I change background image color in PDF using itextsharp

I am using itextsharp for creating pdf and its working good, but now when I am trying to add a background image (as a watermark), and I want to change image color to black and white but don't know how doing that.我正在使用 itextsharp 来创建 pdf 并且它工作得很好,但是现在当我尝试添加背景图像(作为水印)时,我想将图像颜色更改为黑白,但不知道该怎么做。 I am posting screenshot and also code which I am using for added background image.我正在发布屏幕截图以及用于添加背景图像的代码。

在此处输入图片说明

Code :代码 :

public class PdfWriterEvents : IPdfPageEvent
        {
            string watermarkText = string.Empty;

            public PdfWriterEvents(string watermark)
            {
                watermarkText = watermark;
            }
            public void OnStartPage(PdfWriter writer, Document document)
            {
                float width = document.PageSize.Width;
                float height = document.PageSize.Height;
                try
                {
                    PdfContentByte under = writer.DirectContentUnder;
                    Image image = Image.GetInstance(watermarkText);                     
                    image.ScaleToFit(275f, 275f);
                    image.SetAbsolutePosition(150, 300);
                    under.AddImage(image);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                }
            }
            public void OnEndPage(PdfWriter writer, Document document) { }
            public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { }
            public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { }
            public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { }
            public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { }
            public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { }
            public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { }
            public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { }
            public void OnOpenDocument(PdfWriter writer, Document document) { }
            public void OnCloseDocument(PdfWriter writer, Document document) { }
        }

For call this :对于调用这个:

writer.PageEvent = new PdfWriterEvents(LogoImage);

So How can I change color to black and white like normal watermark image.那么如何像普通水印图像一样将颜色更改为黑白。

Thank you !谢谢 !

You can change the image color in two ways:您可以通过两种方式更改图像颜色:

  1. The obviously the easiest one: Use an image editor like MS Paint or Adobe Photoshop to change the Image content color.显然是最简单的一种:使用像 MS Paint 或 Adob​​e Photoshop 这样的图像编辑器来更改图像内容颜色。

  2. At runtime, as you stated in comments: " I want to know is there any other option can able to change color of image by back-end code using itextsharp ".在运行时,正如您在评论中所述:“我想知道是否还有其他选项可以通过后端代码使用 itextsharp 更改图像的颜色”。 Instead of using itextsharp , you can try the below code:您可以尝试以下代码,而不是使用itextsharp


static void Main(string[] args)
{
    try
    {
        Bitmap bmp = null;
        //The Source Directory in debug\bin\Big\
        string[] files = Directory.GetFiles("Big\\");
        foreach (string filename in files)
        {
           bmp = (Bitmap)Image.FromFile(filename);                    
           bmp = ChangeColor(bmp);
           string[] spliter = filename.Split('\\');
           //Destination Directory debug\bin\BigGreen\
           bmp.Save("BigGreen\\" + spliter[1]);
        }                                                 
     }
     catch (System.Exception ex)
     {
        Console.WriteLine(ex.ToString());
     }            
}        

public static Bitmap ChangeColor(Bitmap scrBitmap)
{
    //You can change your new color here. Red,Green,LawnGreen any..
    Color newColor = Color.Red;
    Color actualColor;            
    //make an empty bitmap the same size as scrBitmap
    Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
    for (int i = 0; i < scrBitmap.Width; i++)
    {
       for (int j = 0; j < scrBitmap.Height; j++)
       {
         //get the pixel from the scrBitmap image
         actualColor = scrBitmap.GetPixel(i, j);
         // > 150 because.. Images edges can be of low pixel color. if we set all pixel color to new then there will be no smoothness left.
         if (actualColor.A > 150)
             newBitmap.SetPixel(i, j, newColor);
         else
             newBitmap.SetPixel(i, j, actualColor);
      }
   }            
   return newBitmap;
}

Credits: DareDevil's answer积分: DareDevil 的回答


You can edit your image using the provided method.您可以使用提供的方法编辑图像。

PS: While you are done and satisfied with the result, upvote @DareDevil's answer, it's a brilliant find! PS:当您完成并对结果感到满意时,请为@DareDevil 的回答点赞,这是一个绝妙的发现!

To start with, you used OnStartPage to create the background.首先,您使用OnStartPage创建背景。 This actually is the wrong thing to do.这实际上是错误的做法。 iText developers have stressed again and again that no content shall be added to the document in OnStartPage . iText 开发者一再强调,在OnStartPage不得向文档中添加任何内容。 Instead one should use OnEndPage which in your case does not impose any problem, so you should really do so.相反,应该使用OnEndPage ,在您的情况下它不会强加任何问题,因此您真的应该这样做。


If you have a single bitmap only, the best way surely is to open that bitmap in some image manipulation software and then change the colors to make the image optimal as watermark background.如果您只有一个位图,最好的方法当然是在某些图像处理软件中打开该位图,然后更改颜色以使图像最佳作为水印背景。

If on the other hand you have many possible images to use as background, probably you even get an individual image for each new document, then you cannot tweak each image to its optimum manually anymore.另一方面,如果您有许多可能的图像用作背景,可能您甚至为每个新文档都获得了一个单独的图像,那么您就无法再手动将每个图像调整到最佳状态。 Instead you can either manipulate the bitmap itself by some service or you can use PDF specific features to manipulate the image appearance.相反,您可以通过某些服务操作位图本身,也可以使用 PDF 特定功能来操作图像外观。

Eg with your page event listener I get this:例如,使用您的页面事件侦听器,我得到了以下信息:

背景中的原始绿色图像

Covering the background with white using blend mode Hue this becomes:使用混合模式色相用白色覆盖背景变成:

将图像颜色色调更改为白色

That appears pretty dark but we can lighten it up covering the background with light gray in blend mode Screen :这看起来很暗,但我们可以在混合模式Screen中用浅灰色将其照亮,覆盖背景:

变亮的图像

To do so I moved the code from your PdfWriterEvents method OnStartPage to OnEndPage (see the start of my answer) and changed it like this:为此,我将代码从您的PdfWriterEvents方法OnStartPage移至OnEndPage (请参阅我的答案的开头)并将其更改如下:

public void OnEndPage(PdfWriter writer, Document document)
{
    float width = document.PageSize.Width;
    float height = document.PageSize.Height;
    try
    {
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(watermarkText);
        image.ScaleToFit(275f, 275f);
        image.SetAbsolutePosition(150, 300);

        PdfGState gStateHue = new PdfGState();
        gStateHue.BlendMode = new PdfName("Hue");

        PdfGState gStateScreen = new PdfGState();
        gStateScreen.BlendMode = new PdfName("Screen");

        PdfContentByte under = writer.DirectContentUnder;
        under.SaveState();
        under.SetColorFill(BaseColor.WHITE);
        under.Rectangle(document.PageSize.Left, document.PageSize.Bottom, document.PageSize.Width, document.PageSize.Height);
        under.Fill();
        under.AddImage(image);
        under.SetGState(gStateHue);
        under.SetColorFill(BaseColor.WHITE);
        under.Rectangle(document.PageSize.Left, document.PageSize.Bottom, document.PageSize.Width, document.PageSize.Height);
        under.Fill();
        under.SetGState(gStateScreen);
        under.SetColorFill(BaseColor.LIGHT_GRAY);
        under.Rectangle(document.PageSize.Left, document.PageSize.Bottom, document.PageSize.Width, document.PageSize.Height);
        under.Fill();
        under.RestoreState();
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

I copied the image from IconArchive .我从IconArchive复制了图像。

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

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