Get text from pdf java

How to Extract text from PDF in Java

First, you’re required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project’s pom.xml file.

repositories> repository> id>com.e-iceblueid> name>e-icebluename> url>https://repo.e-iceblue.com/nexus/content/groups/public/ repository> repositories> dependencies> dependency> groupId>e-icebluegroupId> artifactId>spire.pdfartifactId> version>8.7.0version> dependency> dependencies> 

Extract Text from PDF using Java

Spire.PDF offers PdfPageBase.extractText() method to extract the text from all the PDF pages. Here are the steps of how to extract text from all pages of PDF document.

  • Create a PdfDocument instance.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Create a StringBuilder object.
  • Loop through all the pages of PDF and use PdfPageBase.extractText() method to extract text, then append the data to the StringBuilder instance using StringBuilder.append() method.
  • Write the extracted data to a txt document using FileWriter.write() method.
import com.spire.pdf.*; import java.io.*; public class extractTextfromPDF  public static void main(String[] args) throws Exception  //Create a Pdf file PdfDocument pdf = new PdfDocument(); //Load the file from disk pdf.loadFromFile("PDFSample.pdf"); //Create a StringBuilder instance StringBuilder sb = new StringBuilder(); PdfPageBase page; //Traverse all the pages in the document. for (int i = 0; i  pdf.getPages().getCount(); i++)  page = pdf.getPages().get(i); //Extract the text from the pdf pages sb.append(page.extractText(true)); > FileWriter writer; try  //Create a new txt file to save the extracted text writer = new FileWriter("ExtractText.txt"); writer.write(sb.toString()); writer.flush(); > catch (IOException e)  e.printStackTrace(); > pdf.close(); > > 

Extract text from all pages of PDF

Extract Text from Specific Page in PDF

Here are the steps to extract the text from a specific page of PDF.

  • Create a PdfDocument instance and load a sample PDF file using PdfDocument.loadFromFile() method.
  • Create a StringBuilder object.
  • Get the first page of PDF using PdfDocument.getPages().get(0) method.
  • Use page.extractText() method to extract text from the first page, then append the data to the StringBuilder instance using StringBuilder.append() method.
  • Write the extracted data to a txt document using FileWriter.write() method.
import com.spire.pdf.*; import java.io.*; public class extractTextFromParticularPage  public static void main(String[] args) throws Exception  //Create a Pdf file PdfDocument pdf = new PdfDocument(); //Load the file from disk pdf.loadFromFile("PDFSample.pdf"); //Create a StringBuilder instance StringBuilder sb = new StringBuilder(); //Get the first page PdfPageBase page = pdf.getPages().get(0); //Extract the text and keep white space sb.append(page.extractText(true)); FileWriter writer; try  //Create a new txt file to save the extracted text writer = new FileWriter("extractTextFromParticularPage.txt"); writer.write(sb.toString()); writer.flush(); > catch (IOException e)  e.printStackTrace(); > pdf.close(); > > 

Extract text from the specific page of PDF

Extract Text from Specific Area in PDF

Here are the steps to extract the text from a specific rectangle area on a PDF page.

  • Create a PdfDocument instance and load a sample PDF file using PdfDocument.loadFromFile() method.
  • Create a StringBuilder object.
  • Get the first page of PDF using PdfDocument.getPages().get(0) method.
  • Use page.extractText(new Rectangle2D.Float(x, y, width, height)) method to extract the text from the specific rectangle area, then append the data to the StringBuilder instance using StringBuilder.append() method.
  • Write the extracted data to a txt document using FileWriter.write() method.
import com.spire.pdf.*; import java.io.*; import java.awt.geom.Rectangle2D; public class extractTextFromSpecificArea  public static void main(String[] args) throws Exception  //Create a Pdf file PdfDocument pdf = new PdfDocument(); //Load the file from disk pdf.loadFromFile("PDFSample.pdf"); //Create a StringBuilder instance StringBuilder sb = new StringBuilder(); //Get the first page PdfPageBase page = pdf.getPages().get(0); //Extract text from a specific rectangular area within the page sb.append(page.extractText(new Rectangle2D.Float(60, 120, 500, 220))); FileWriter writer; try  //Create a new txt file to save the extracted text writer = new FileWriter("extractTextFromParticularArea.txt"); writer.write(sb.toString()); writer.flush(); > catch (IOException e)  e.printStackTrace(); > pdf.close(); > > 

Extract text from specific area of PDF

Extract Highlighted Text from PDF Document

Spire.PDF also supports to extract highlighted text from PDF document.

  • Create a PdfDocument instance and load a sample PDF file using PdfDocument.loadFromFile() method.
  • Create a StringBuilder object.
  • Get the first page of PDF using PdfDocument.getPages().get(0) method.
  • Get the annotation collection of the first page of the document by using page.getAnnotationsWidget().
  • Loop through the pop-up annotations, after extract data from each annotation using annotations.get(int).getText() method, then append the data to the StringBuilder instance using StringBuilder.append() method.
  • Write the extracted data to a txt document using Writer.write() method.
import com.spire.pdf.*; import com.spire.pdf.annotations.PdfTextMarkupAnnotationWidget; import java.io.*; public class extractHighlightedText  public static void main(String[] args) throws Exception  //Create a Pdf file PdfDocument pdf = new PdfDocument(); //Load the file from disk pdf.loadFromFile("PDFSample0.pdf"); //Create a StringBuilder instance StringBuilder sb = new StringBuilder(); //Get the first page PdfPageBase page = pdf.getPages().get(0); for (int i = 0; i  page.getAnnotationsWidget().getCount(); i++)  if (page.getAnnotationsWidget().get(i) instanceof PdfTextMarkupAnnotationWidget)  PdfTextMarkupAnnotationWidget textMarkupAnnotation = (PdfTextMarkupAnnotationWidget) page.getAnnotationsWidget().get(i); sb.append(page.extractText(textMarkupAnnotation.getBounds())); > > FileWriter writer; try  //Create a new txt file to save the extracted text writer = new FileWriter("extractHilightedText.txt"); writer.write(sb.toString()); writer.flush(); > catch (IOException e)  e.printStackTrace(); > pdf.close(); > > 

Extract highlighted text from PDF

Conclusion

In this article, we have demonstrated how to extract text from PDF using Java. With Spire.PDF for Java, we could extract text from PDF file for different scenarios, such as extracting all the text from a PDF; only extract the text from a specific page, or a specific page area. And we can also only get the highlighted text from the PDF. You can check the PDF forum for more features to operate the PDF files.

Источник

IText: вытаскиваем текст из PDF

image

Недавно столкнулся с задачей: научиться вытаскивать текст из PDF запоминая его позицию на странице. И, конечно же, в несложной поначалу задаче вылезли подводные камни. Как же в итоге получилось это решить? Ответ под катом.

Немного о PDF формате

PDF (Portable Document Format) — популярный межплатформенный формат документов, использующий язык PostScript. Основное его предназначение — корректное отображение на различных операционных системах и т. д.

  • слова могут быть нелогично разбиты на части. Например отображение слова «алгоритмы» записано, грубо говоря, тремя частями: отобрази «алг» «орит» «мы»
  • строчки в тексте и слова в строчках могут отображаться совсем не в том порядке, как мы привыкли читать
  • в одних документах пробелы задаются явно (т.е. есть команды содержащие ‘ ‘), в других — они образуются при помощи того, что соседние слова отображаются друг от друга на некотором расстоянии

Потому желание парсить pdf самостоятельно пропало моментально.
p.s. от всего этого невольно вспомнилась цитата

Затем, поигравшись с несколькими библиотеками (pdfminer, pdfbox), я решил остановиться на iText.

Немного про iText

iText: библиотека на Java, предназначенная для работы с pdf (также есть версия на C#: iTextSharp). Начиная с версии 5.0.0 свободно распространяется по лицензии AGPL (обязывающая предоставлять пользователям возможность получения исходного кода), но также есть и коммерческая версия. Снабжена неплохой документацией. А тем, кто хочет ознакомиться с библиотекой по-лучше, советую книгу от создателя библиотеки «iText in Action».

Простой способ вытащить текст из PDF

Вот этот код неплохо извлекает текст из PDF, но не предоставляет какой-либо информации, о его расположении в документе.

public class SimpleTextExtractor < public static void main(String[] args) throws IOException < // считаем, что программе передается один аргумент - имя файла PdfReader reader = new PdfReader(args[0]); // не забываем, что нумерация страниц в PDF начинается с единицы. for (int i = 1; i // убираем за собой reader.close(); > > 

А теперь разберемся во всем по порядку.

PdfReader — класс, читающий PDF. Умеет конструироваться не только от имени файла, но и от InputStream, Url или RandomAccessFileOrArray.

TextExtractionStrategy — интерфейс, определяющий стратегию извлечения текста. Подробнее о нем — ниже.

SimpleTextExtractionStrategy — класс, реализующий TextExtractionStrategy. Несмотря на название, очень неплохо вытаскивает текст из PDF (справляется с переменчивой структурой PDF, а именно, если сначала текст идет в двух колонках, а затем переключается на обычное написание во всю страницу.

PdfTextExtractor — статический класс, содержащий лишь 2 метода getTextFromPage с одной разницей — указываем мы явно стратегию извлечения текста или нет.

Вытаскиваем текст, запоминая координаты

Для этого нам нужно обратить внимание на интерфейс TextExtractionStrategy. А именно на эти две функции:

public void renderText(TextRenderInfo renderInfo)

— при вызове getTextFromPage эта функция вызывается при каждой команде, отображающей текст. В TextRenderInfo хранится вся необходимая информация: текст, шрифт, координаты.

public string GetResultantText()

— эта функция вызывается перед окончанием getTextFromPage и ее результат вернется пользователю.

В качестве образца, научимся простейшим образом вытаскивать пары вида для каждой строки на странице.

public class TextExtractionStrategyImpl implements TextExtractionStrategy < private TreeMap> textMap; public TextExtractionStrategyImpl() < // reverseOrder используется потому что координата y на странице идет снизу вверх textMap = new TreeMap>(Collections.reverseOrder()); > @Override public String getResultantText() < StringBuilder stringBuilder = new StringBuilder(); // итерируемся по строкам for (Map.Entry> stringMap: textMap.entrySet()) < // итерируемся по частям внутри строки for (Map.Entryentry: stringMap.getValue().entrySet()) < stringBuilder.append(entry.getValue()); >stringBuilder.append('\n'); > return stringBuilder.toString(); > @Override public void beginTextBlock() <> @Override public void renderText(TextRenderInfo renderInfo) < // вытаскиваем координаты Float x = renderInfo.getBaseline().getStartPoint().get(Vector.I1); Float y = renderInfo.getBaseline().getStartPoint().get(Vector.I2); // если до этого мы не добавляли элементы из этой строчки файла. if (!textMap.containsKey(y)) < textMap.put(y, new TreeMap()); > textMap.get(y).put(x, renderInfo.getText()); > @Override public void endTextBlock() <> @Override public void renderImage(ImageRenderInfo imageRenderInfo) <> // метод для извлечения строчек с их y-координатой ArrayList getStringsWithCoordinates() < ArrayList result = new ArrayList(); for (Map.Entry> stringMap: textMap.entrySet()) < StringBuilder stringBuilder = new StringBuilder(); for (Map.Entryentry: stringMap.getValue().entrySet()) < stringBuilder.append(entry.getValue()); >result.add(new Pair(stringMap.getKey(), stringBuilder.toString())); > return result; > > 

А основной код выглядит так:

public class TextExtractor < public static void main(String[] args) throws IOException < PdfReader reader = new PdfReader(args[0]); for (int i = 1; i pair: strategy.getStringsWithCoordinates()) < System.out.println(pair.getKey().toString() + " " + pair.getValue()); >> reader.close(); > > 
Примечания

Конечно, для хорошего извлечения текста надо добавить всякие фишки для корректной обработки текста в нескольких колонках, обработки пробелов не заданных явно и т.д., но я не хочу в пределах этой статьи углубляться в такие детали.

И еще хотелось бы отметить, что это лишь малая часть возможностей библиотеки. При помощи нее можно создавать документы, добавлять текст и изображения в уже существующие (включая водяные знаки).

И ссылка на репозиторий (ох уж этот AGPL)

Источник

Извлечь текст из PDF в Java

В последних работах необходимо извлечь текстовое содержание, содержащееся в огромном PDF-документе. После поиска информации в Интернете я обнаружил, что Free Spire.PDF для Java может помочь мне выполнить эту операцию с помощью простого кода. Ниже приведен код Java, используемый в процессе.

Основные шаги

1. Сначала установите пакет JAR через репозиторий Maven. Код для настройки файла pom.xml выглядит следующим образом:

  com.e-iceblue e-iceblue http://repo.e-iceblue.com/nexus/content/groups/public/    e-iceblue spire.pdf.free 2.6.3   

2. Создайте новый Java-класс в приложении Java (здесь я назвал ExtractText), затем введите соответствующий код Java и запустите

Исходный документ в формате PDF выглядит следующим образом:

image

import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import java.io.*; public class ExtractText < public static void main(String[] args) < //Создайте экземпляр PdfDocument PdfDocument doc=new PdfDocument(); //Загрузите файл PDF doc.loadFromFile("document1.pdf"); //Создать экземпляр StringBuilder StringBuilder sb=new StringBuilder(); PdfPageBase page; //Перебирайте страницы PDF и получайте текст каждой страницы for(int i=0;iFileWriter writer; try < //Написать текст в текстовый файл writer = new FileWriter("ExtractText.txt"); writer.write(sb.toString()); writer.flush(); >catch (IOException e) < e.printStackTrace(); >doc.close(); > > 

Источник

Читайте также:  Image alt with css
Оцените статью