将System.Drawing.Image映射到iTextSharp中正确的PdfName.COLORSPACE和PdfName.FILTER

时间:2015-04-01 15:03:06

标签: itextsharp

我正在使用iTextSharp使用修改后的System.Drawing.Image更新PDF中的图像对象。如何根据System.Drawing.Image正确设置PdfName.COLORSPACE和PdfName.FILTER?我不确定哪个System.Drawing.Image属性可以用于映射。

private void SetImageData(PdfImageObject pdfImage, System.Drawing.Image image, byte[] imageData)
{
    PRStream imgStream = (PRStream)pdfImage.GetDictionary();
    imgStream.Clear();
    imgStream.SetData(imageData, false, PRStream.NO_COMPRESSION);
    imgStream.Put(PdfName.TYPE, PdfName.XOBJECT);
    imgStream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
    imgStream.Put(PdfName.WIDTH, new PdfNumber(image.Width));
    imgStream.Put(PdfName.HEIGHT, new PdfNumber(image.Height));
    imgStream.Put(PdfName.LENGTH, new PdfNumber(imageData.LongLength));

    // Not sure how to properly set these entries based on the image properties
    imgStream.Put(PdfName.BITSPERCOMPONENT, 8);
    imgStream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
    imgStream.Put(PdfName.FILTER, PdfName.DCTDECODE);
}

1 个答案:

答案 0 :(得分:1)

我接受了Chris Haas的建议,并将System.Drawing.Image编写为临时PDF,然后将其作为PdfImageObject读回来。

using (MemoryStream ms = new MemoryStream())
{
    using (iTextSharp.text.Document doc = new iTextSharp.text.Document())
    {
        using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc))
        {
            doc.Open();

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(drawingImage, drawingImage.RawFormat);
            image.SimplifyColorspace();

            doc.Add(image);
            doc.Close();
        }
    }
    ... code that opens the mem stream with PdfReader and retrieves the image as PdfImageObj...
}

虽然有效,但似乎是为了作弊而分配。我在调用doc.Add(image)时逐步完成了代码,发现最终从iTextSharp.text.Image对象创建了一个PdfImage对象,而PdfImage对象包含了我需要的所有字典条目。因此,我决定在原作弊中削减一些角落,并将其作为我的最终解决方案:

private void SetImageData(PdfImageObject pdfImageObj, byte[] imageData)
{
    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageData);
    image.SimplifyColorSpace();

    PdfImage tempPdfImage = new PdfImage(image, "TempImg", null);

    PRStream imgStream = (PRStream)pdfImageObj.GetDictionary();
    imgStream.Clear();
    imgStream.SetDataRaw(imageData);
    imgStream.Merge(tempPdfImage);
}