内容目录
示例代码如下:
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;
}
}
文章评论