【发布时间】:2021-05-07 19:08:36
【问题描述】:
我有一个网站,我的客户可以在其中上传他们的文件(主要是 PDF)。我希望能够使 PDF 可搜索,但我不希望更改 PDF 的外观。我已经尝试创建一个 .NET 端点来实现这一点,我可以发布到。
我已经尝试将 iTextSharp 与 Tesseract 结合使用,但它们都没有给我我想要的东西。这是我尝试过的代码:
使用tesseract从pdf中获取文本:
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
using (var img = Pix.LoadFromFile(testImagePath))
using (var page = engine.Process(img))
{
var text = page.GetText();
}
然后使用 iTextSharp 从旧版本生成 PDF:
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
但是,我在生成所需的输出时遇到了问题。有没有更简单的方法来实现我正在寻找的东西?这是我试图使其可搜索的 PDF 示例。我不想丢失 PDF 的图像或字体/样式。我只是想让它变得可搜索:
【问题讨论】:
-
我在您的问题中添加了
itext标签。正如我在您的其他问题下评论的那样,iText Software 可能会为您提供帮助。但是,这超出了 Stack Overflow 上可以做的事情,所以我建议你直接联系公司。 -
哦,您还可以获得 iText 7 + pdfOCR 的 30 天免费试用。更多itextpdf.com/en/products/itext-7/pdf-ocr-text-recognition
标签: c# pdf itext ocr tesseract