如何仅使 PDF 图章的白色部分透明?

How to make only the white part of a PDF stamp transparent?

使用 iTextSharp,我想在 PDF 上盖上图章并使其透明。邮票上有彩色文本(各种颜色),当整个图像透明时变得难以阅读,所以我不想让彩色文本透明 - 只有邮票矩形中的白色背景。

基于this answer,我尝试了以下代码:

public void addImage(PdfDictionary oldAnnot, string imagePath, 
                         int pageNumber,iTextSharp.text.Rectangle someRectangle) {
    Stream inputImageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read);
    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
    PdfAnnotation pdfStamp = PdfAnnotation.CreateStamp(pdfStamper.Writer, someRectangle, null, Guid.NewGuid().ToString());
    image.SetAbsolutePosition(0, 0);
    PdfAppearance app = pdfStamper.GetOverContent(pageNumber).CreateAppearance(image.Width, image.Height);
    app.SaveState();
    PdfGState state = new PdfGState();
    state.FillOpacity = 0.1f;
    app.SetGState(state);
    app.AddImage(image);
    app.RestoreState();
    pdfStamp.SetAppearance(PdfName.N, app);
    pdfStamp.SetPage();
    pdfStamper.AddAnnotation(pdfStamp, pageNumber);
}

但是,这会使图像的彩色部分变得半透明。如何只让图片的空白背景透明,彩色部分不透明?

谢谢。

您实际上是在要求 Colour Key Masking PDF 功能。遗憾

When colour key masking is specified, the use of a DCTDecode or lossy JPXDecode filter for the stream can produce unexpected results.

(第 8.9.6.4 节 – 色键掩码 – ISO 32000-1)

由于您有 JPEG,并且 JPEG 通常使用 DCTDecode 滤镜嵌入到 PDF 中,颜色键掩码可能无法按预期工作。


您可能想尝试使用不同的混合模式,而不是使用透明度,例如加深乘法

Multiply B(cb, cs) = cb * cs

NOTE 1 Multiplies the backdrop and source colour values.

NOTE 2 The result colour is always at least as dark as either of the two constituent colours. Multiplying any colour with black produces black; multiplying with white leaves the original colour unchanged. Painting successive overlapping objects with a colour other than black or white produces progressively darker colours.

Darken B(cb, cs) = min(cb, cs)

NOTE 6 Selects the darker of the backdrop and source colours.

NOTE 7 The backdrop is replaced with the source where the source is darker; otherwise, it is left unchanged.

(Table 136 – 标准可分离混合模式 – ISO 32000-1)

要 select 混合模式,您可以像已经使用的那样使用 PdfGState,但不要设置不透明度

state.FillOpacity = 0.1f;

你设置混合模式

state.BlendMode = PdfGState.BM_MULTIPLY;

state.BlendMode = PdfGState.BM_DARKEN;