我正在使用PDFSharp.NET库为PDF文件列表添加水印。一切正常,网站上有很多示例。
http://www.pdfsharp.net/wiki/Graphics-sample.ashx
我最后需要做的是在PDF页面的中间添加一个很大的公司徽标。
我可以使用PNG,这样设置为透明的区域就不会“覆盖” PDF页面“。
该pdf不是使用PDFSharp生成的,而是“图像” PDF。
因此,我需要的是,除了可以使用的透明性之外,还能够设置一些图像不透明度!
放置图像的代码就是这个:
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
XImage image = XImage.FromFile(mypath);
gfx.DrawImage(image, pwidth/2-image.PixelWidth/2, pheight/2 image.PixelHeight/2);
gfx.Dispose();
任何人都已经面对过吗?
[使用PDFsharp绘制图像时,我不知道如何更改图像的不透明度(而且恐怕无法完成)。
因此,我只用图像处理器打开徽标(PNG)并在此处设置不透明度。
我现在也在考虑在水印(companyLogo)上放置pdf表格。下面的代码使您可以更改不透明度。
PDFSharp无法更改图像不透明度。您可以做的就是将您提供的图像锐化为PDF。
private void DrawGraphics()
{
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
Image myTransparenImage = SetImageOpacity(Image.FromFile("MyPath"), (float)opacityYouwant); // opacityYouWant has to be a value between 0.0 and 1.0
XImage image = XImage.FromBitmapSource(Convert(myTransparenImage));
gfx.DrawImage(image, pwidth / 2 - image.PixelWidth / 2, pheight / 2 image.PixelHeight / 2);
gfx.Dispose();
}
public Image SetImageOpacity(Image image, float opacity)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix();
//set the opacity
matrix.Matrix33 = opacity;
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
public BitmapImage Convert(Image img)
{
using (var memory = new MemoryStream())
{
img.Save(memory, ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}