使用iTextSharp将图像转换为PDF保留剪切路径

我们希望以编程方式将图像批量转换为PDF。 到目前为止看起来我们将使用iTextSharp,但我们遇到了带剪切路径的JPG图像问题。 我们在测试中使用以下代码:

using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document doc = new Document()) { using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(source); image.SetAbsolutePosition(0, 0); doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, image.Width, image.Height, 0)); doc.NewPage(); writer.DirectContent.AddImage(image,false); doc.Close(); } } } 

JPG图像中的剪切路径似乎只是被丢弃了。 有没有办法保留剪切路径? 另外,当调用AddImage时,InlineImage有一个选项,任何人都知道这是做什么的?

iText将JPG的字节直接复制到PDF中。 不会更改单个字节。 如果你说你的JPG有剪切路径(我从未听说过这样的事情)并且你没有在PDF中看到这个function,那么你将面临PDF固有的局限性,而不是iText。 iText甚至没有查看JPG字节:它只是使用filterDCTDecode创建一个PDF流对象。

将图像添加到PDF 之前,您必须应用剪切路径。 您可能知道,PDF不支持PNG,PNG支持透明度。 当iText遇到透明的PNG时,它会处理PNG。 它创建了两个图像:一个使用/FlateDecode不透明图像和一个使用/FlateDecode单色图像。 添加单色图像作为其掩模的不透明图像以获得透明度。 我想你必须以类似的方式预处理你的JPG。

关于内联图片:

不要使用内嵌图像:使用内嵌图像意味着图像存储在PDF的内容流中,而不是存储为Image XObject(这是在PDF中存储图像的最佳方式)。 内嵌图像只能用于大小为4 KB或更小的图像。 PDF 2.0中将禁止使用更大的内嵌图像。

额外评论:

我想我的代码中存在问题。 您正在创建页面大小为A4的文档:

 Document doc = new Document() 

如果未将参数传递给Document构造函数,则A4是默认大小。 之后,您尝试更改页面大小,如下所示:

 doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, image.Width, image.Height, 0)); doc.NewPage(); 

但是:由于您尚未向第一页添加任何内容,因此将忽略NewPage()方法并且不会更改页面大小。 您仍将在第1页上使用A4尺寸。

 iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(source); using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document doc = new Document(image)) { using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); image.SetAbsolutePosition(0, 0); writer.DirectContent.AddImage(image); doc.Close(); } } }