Method for Loop Scanning to Find Elements in PdfSharp

2023年10月18日 54点热度 0人点赞 0条评论
内容目录

The sample code is as follows:

			var oldPdf = PdfReader.Open("测试.pdf");
			foreach (var oldPage in oldPdf.Pages)
			{
				// Insert a page
				PdfPage newPage = newPdf.AddPage();

				// Query elements
				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;
					
					// Determine the element type, then proceed to next step for parsing, such as images
					if(xObject.Elements.GetString("/Subtype") == "/Image")
					{
						ExportImage(xObject);
					}
				}
			}

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

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

痴者工良

高级程序员劝退师

文章评论