我有一个程序,以前使用 ChatGPT 来扫描文档,并在页面包含图表(例如表格或图表)时发出警报。由于 ChatGPT 已停止通过 API 接受图像,我一直在使用 ChatGPT 网站手动处理这些页面,这是相当耗时且冗长的。
我想重新自动化这个过程。不幸的是,我尝试过的 OCR 服务(例如 Azure OCR、Amazon Reckognition 和 Google Cloud Vision OCR)不具备相同的功能。
我尝试使用以下代码来执行此操作:
using System;
using System.Collections.Generic;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
namespace PdfImageDetectionTest
{
class Program
{
public static List<int> GetPagesWithImages(string pdfPath)
{
List<int> pagesWithImages = new List<int>();
// Load the PDF document
using (PdfReader pdfReader = new PdfReader(pdfPath))
using (PdfDocument pdfDocument = new PdfDocument(pdfReader))
{
int totalPages = pdfDocument.GetNumberOfPages();
for (int i = 1; i <= totalPages; i++)
{
// Use a custom listener to detect images
ImageDetectionListener imageListener = new ImageDetectionListener();
PdfCanvasProcessor processor = new PdfCanvasProcessor(imageListener);
processor.ProcessPageContent(pdfDocument.GetPage(i));
// If the listener found any images, add the page number to the list
if (imageListener.HasImage())
{
pagesWithImages.Add(i);
}
}
}
return pagesWithImages;
}
public static void Main(string[] args)
{
// Path to your test PDF file
string pdfPath = "path/to/your/test-file.pdf";
List<int> pagesWithImages = GetPagesWithImages(pdfPath);
if (pagesWithImages.Count > 0)
{
Console.WriteLine("Pages with images: " + string.Join(", ", pagesWithImages));
}
else
{
Console.WriteLine("No pages contain images.");
}
// Keep console window open
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
public class ImageDetectionListener : IEventListener
{
private bool foundImage = false;
public void EventOccurred(IEventData data, EventType type)
{
if (type == EventType.RENDER_IMAGE)
{
foundImage = true; // Image found!
}
}
public bool HasImage()
{
return foundImage;
}
public ICollection<EventType> GetSupportedEvents()
{
// Only listen for image rendering events
return new HashSet<EventType> { EventType.RENDER_IMAGE };
}
}
}
但是由于整个文件是扫描文档,因此它会将所有页面识别为包含图表,而不仅仅是我们想要的页面。有没有更简单的方法来做到这一点,或者库/包实际上能够完成我们想要的事情?
我一直在忙着同样的事情。但我从不同的供应商导入发票。据我所知,您可以选择 iText 如何读取文件。例如:
var pdfReader = new PdfReader("file_location");
var reader = new PdfDocument(pdfReader);
var page = reader.GetPage(i);
ITextExtractionStrategy strate = new LocationTextExtractionStrategy();
//Your point of interessed
ILocationExtractionStrategy loc = new RegexBasedLocationExtractionStrategy(""); //Use some regex to detect the image
var processor = new PdfCanvasProcessor(strate);
processor.ProcessPageContent(page);
int nrObjects = reader.GetNumberOfPdfObjects();
for(int i = 0; i < nrObjects; i++)
{
var obj = reader.GetPdfObject(i);
PdfDictionary pd = (PdfDictionary)obj;
// etc etc...
}
这是我迄今为止测试过的。我也收到了图像,但这不是我的目标。所以也许这会对您有进一步的帮助。