Lar*_*rén 2 c# jpeg clipping itext itextsharp
我们希望以编程方式将图像批量转换为 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
JPG 图像中的剪切路径似乎只是被丢弃了。有没有办法保留剪切路径?此外,在调用 AddImage 时,有一个 InlineImage 选项,有人知道这是做什么的吗?
iText 将 JPG 的字节直接复制到 PDF 中。没有一个字节被改变。如果您说您的 JPG 具有剪切路径(我从未听说过这样的事情)并且您在 PDF 中没有看到该功能,那么您将面临 PDF 固有的限制,而不是 iText。iText 甚至不查看 JPG 字节:它只是创建一个带有过滤器 DCTDecode 的 PDF 流对象。
在将图像添加到 PDF之前,您必须应用剪切路径。您可能知道,PDF 不支持 PNG,而 PNG 支持透明度。当 iText 遇到透明的 PNG 时,它会处理 PNG。它创建了两个图像:一个不透明的图像使用/FlateDecode和一个使用 的单色图像/FlateDecode。不透明图像加上单色图像作为其蒙版以获得透明度。我想您必须以类似的方式预处理您的 JPG。
关于内嵌图像:
不要使用内嵌图像:使用内嵌图像意味着图像存储在 PDF 的内容流中,而不是存储为图像 XObject(这是在 PDF 中存储图像的最佳方式)。内嵌图片只能用于大小不超过 4 KB 的图片。PDF 2.0 中将禁止使用较大的内嵌图像。
补充说明:
我想我在你的代码中看到了一个问题。您正在创建一个页面大小为 A4 的文档:
Document doc = new Document()
Run Code Online (Sandbox Code Playgroud)
当您不向Document构造函数传递参数时,A4 是默认大小。之后,您尝试像这样更改页面大小:
doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, image.Width, image.Height, 0));
doc.NewPage();
Run Code Online (Sandbox Code Playgroud)
但是:由于您尚未向第一页添加任何内容,因此该NewPage()方法将被忽略且页面大小不会更改。您仍将在 A4 尺寸的第 1 页上。
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)