PdfSharp 循环扫描查找元素的方法

2023年10月18日 663点热度 0人点赞 0条评论
内容纲要

示例代码如下:

            var oldPdf = PdfReader.Open("测试.pdf");
            foreach (var oldPage in oldPdf.Pages)
            {
                // 插入一个页面
                PdfPage newPage = newPdf.AddPage();

                // 查询元素
                PdfDictionary? resources = oldPage.Elements.GetDictionary("/Resources");
                if (resources == null) continue;
                PdfDictionary? xObjects = resources.Elements.GetDictionary("/XObject");
                if (xObjects == null) continue;
                ICollection<PdfItem?> elementItems = xObjects.Elements.Values;
                foreach (var pdfItem in elementItems)
                {
                    if (pdfItem is not PdfReference reference) continue;
                    if (reference.Value is not PdfDictionary xObject) continue;

                    // 判断元素类型,后进入下一步解析,如图片
                    if(xObject.Elements.GetString("/Subtype") == "/Image")
                    {
                        ExportImage(xObject);
                    }
                }
            }

// 解析元素
    static void ExportImage(PdfDictionary image)
    {
        string filter = image.Elements.GetName("/Filter");
        switch (filter)
        {
            case "/DCTDecode":
                ExportJpegImage(image);
                break;

            case "/FlateDecode":
                ExportAsPngImage(image);
                break;
        }
    }

痴者工良

高级程序员劝退师

文章评论