Парсер pdf в excel

Задача: 

Создать таблицу цен на грузоперевозки между городами России,
взяв данные из ПДФ файлов с сайта транспортной компании.

Описание: 

В видеоролике подробно рассказано, как парсер выполняет сбор данных из файлов PDF.
(парсер загружает ПДФ файлы с сайта, но может аналогично обрабатывать и файлы PDF из папки)

ВАЖНО: Для работы парсера требуется, чтобы браузер Internet Explorer умел открывать файлы ПДФ
Если Internet Explorer не умеет открывать файлы PDF, то необходимо установить расширение Adobe Acrobat Reader для браузеров.
Скачать это расширение можно по ссылке: https://get.adobe.com/ru/reader/


Download Article


Download Article

There are many ways to convert an entire PDF to an Excel document, but extracting only a certain section of data is a little harder. Thankfully, there are still a few different ways to do so, including manually copying and pasting the data, using free online tools like Docparser, and using paid tools like Adobe Acrobat Pro DC and PanaForma. This wikiHow article will teach you how to export specific data in a PDF to Excel.

  1. Image titled Extract Specific Data from PDF to Excel Step 1

    1

    Open the PDF in your PDF reader. Double-clicking the PDF file will automatically open it in your default PDF reader, such as Preview for macOS or Edge for Windows.

  2. Image titled Extract Specific Data from PDF to Excel Step 2

    2

    Select the data you would like to extract from a PDF. You can select the data by clicking and dragging from the top left of a section to the bottom right. The section should now be highlighted.

    Advertisement

  3. Image titled Extract Specific Data from PDF to Excel Step 3

    3

    Copy the data to your clipboard. Right-click the highlighted section and select Copy.

    • Alternatively, you can copy the data by pressing Command + C on Mac or Control + C on Windows.
  4. Image titled Extract Specific Data from PDF to Excel Step 4

    4

    Open an Excel document and select a number of cells. As before, to quickly select multiple cells, click and drag your mouse from the upper-leftmost cell to the lower-rightmost cell.

    • Be sure to select enough cells to fit your data. Otherwise, you will only be able to paste part of the data.
  5. Image titled Extract Specific Data from PDF to Excel Step 5

    5

    Paste the data into the Excel document. Right-click one of the highlighted cells and select Paste. While you will likely have to do some reformatting, you should have data from your PDF in an Excel file!

    • If it does not paste effectively as a group, try copying and pasting it line by line into the desired cell(s).
    • You can also paste your data by pressing Command + V on Mac or Control + V on Windows.
  6. Advertisement

  1. Image titled Extract Specific Data from PDF to Excel Step 6

    1

    Sign up for an account at https://app.docparser.com/account/signup. Docparser has a variety of plans, including a free plan that allows you to parse 30 documents per month.

    • You can choose to sign up with an existing Google or Microsoft account or create a new Docparser-specific account.
  2. Image titled Extract Specific Data from PDF to Excel Step 7

    2

    Click Create Document Parser. This blue button is located in the bottom middle of your screen.

  3. Image titled Extract Specific Data from PDF to Excel Step 8

    3

    Type in a name and select a template. If the document you would like to parse does not fit one of the presets, select the Custom option in the middle of the top row.

    • Docparser’s templates will all come with a set of premade rules tailored to that document type, while creating a custom template requires you to set your own rules.
  4. Image titled Extract Specific Data from PDF to Excel Step 9

    4

    Upload a PDF and click Continue. You can choose to either drag and drop a PDF file into the site or click the upload box, then select a file on your computer. Once you have uploaded your PDF(s), click the green button at the top right of the screen.

    • If you would like to convert multiple PDFs with the same rules, continue uploading more files.
  5. Image titled Extract Specific Data from PDF to Excel Step 10

    5

    Watch or skip the parsing rules video. Parsing rules allow you to choose how Docparser reads and converts your PDF. If you would rather not watch the tutorial video, click the “X” at the top right of the pop-up window.

    • The video is barely over a minute and a half in length, so consider watching it to get a better sense of how you can customize the parsing of your PDFs.
  6. Image titled Extract Specific Data from PDF to Excel Step 11

    6

    Follow the tips as they appear on screen. Docparser will start by having you pick the Text Variable Position rule preset, then naming your rule. It will then explain the data that was parsed, where to add filters and narrow that data down, and how to see a preview of your filtered data.

  7. Image titled Extract Specific Data from PDF to Excel Step 12

    7

    Add text filters and adjust each using the “Filtered Result” boxes below. Each box includes a dropdown menu for revising its corresponding filter as well as a preview of your data.

    • To select a specific piece of data, click Add Text Filter, then hover over Crop From Start & End and set a start and end point for the parsing of your document.
  8. Image titled Extract Specific Data from PDF to Excel Step 13

    8

    Click Save Parsing Rule. This green button is in the bottom right of the screen and has a small white check mark icon.

  9. Image titled Extract Specific Data from PDF to Excel Step 14

    9

    Make another parsing rule or leave the editor. If you are done creating rules, click the gray Leave Parsing Editor button. Otherwise, click the blue Create Another Parsing Rule button and continue making rules, then leave the editor and move to the next step.

  10. Image titled Extract Specific Data from PDF to Excel Step 15

    10

    Click the checkbox next to your document’s name. A black check mark should appear.

  11. Image titled Extract Specific Data from PDF to Excel Step 16

    11

    Select Move To Parse Queue from the Perform Action dropdown menu. The dropdown menu can be found at the top left of your screen, directly above the name of your document.

  12. Image titled Extract Specific Data from PDF to Excel Step 17

    12

    Click Ok, wait a minute, and refresh the page. If you do not see your document, it is likely still parsing. Try waiting another minute and switching between tabs in the document parser.

  13. Image titled Extract Specific Data from PDF to Excel Step 18

    13

    Press the file name. This button is on the left side of the page and has an arrow pointing down into technology as its icon.

  14. Image titled Extract Specific Data from PDF to Excel Step 19

    14

    Click Excel Download. You should now have an Excel document containing the selected data from your PDF!

    • You may have to allow downloads on the site before your file begins downloading.
  15. Advertisement

  1. Image titled Extract Specific Data from PDF to Excel Step 20

    1

    Open the desired PDF with Acrobat. If Acrobat is not your default PDF reader, you can use it by right-clicking the file, then selecting Acrobat from the Open With menu.

    • You may have to search for Acrobat in the Open With menu by clicking Other… for Mac or Choose another app for Windows.
  2. Image titled Extract Specific Data from PDF to Excel Step 21

    2

    Select the data you would like to extract. You can select the data by clicking and dragging from the top left of a section to the bottom right. The section should now be highlighted.

  3. Image titled Extract Specific Data from PDF to Excel Step 22

    3

    Right-click your selection and choose Export Selection As…. A new window should appear with a variety of options for exporting the chosen portion of your PDF.[1]

  4. Image titled Extract Specific Data from PDF to Excel Step 23

    4

    Select the XLSX format from the Save As Type list and click Save. You should now have an Excel spreadsheet with specific data from your PDF!

  5. Advertisement

PanaForma is useful when you have many documents in the same format from which you want to extract data.

  1. Image titled Extract Specific Data from PDF to Excel Step 24

    1

    Download and install the PanaForma app (Windows only) — PanaForma has a one-month free trial, and there’s no obligation to continue with a paid plan.

  2. Image titled Extract Specific Data from PDF to Excel Step 25

    2

    Open the PanaForma app, and click Add Folder. This button is located in the top left corner of the app window. In the folder picker, choose the folder on your computer where your PDF files are stored.

  3. Image titled Extract Specific Data from PDF to Excel Step 26

    3

    With the folder added, expand the folder tree to locate the first PDF file you will extract data from. Click the file name in the tree to open the file. You will use this file to create a Template that you will apply to extract data from all the PDFs that share the same format.

  4. Image titled Extract Specific Data from PDF to Excel Step 27

    4

    In the right-hand panel of the app, give your new Template a name, and click Create.

  5. Image titled Extract Specific Data from PDF to Excel Step 28

    5

    Using the mouse, drag a selection box around each data field on the page that you want to extract. In this example, five data fields have been selected.

  6. Image titled Extract Specific Data from PDF to Excel Step 29

    6

    Once you’ve selected all the data fields in your Template, give each field a distinctive name in the right-hand panel.

  7. Image titled Extract Specific Data from PDF to Excel Step 30

    7

    Now apply you Template to all the required PDFs. To do this, select each PDF in the left-hand panel file tree, then select your Template in the «Apply existing Template» drop-down on the right-hand panel, and click Ok. After applying the Template, you can move or resize each field on the page if required, or make manual edits to the extracted data values in the right-hand panel.

  8. Image titled Extract Specific Data from PDF to Excel Step 31

    8

    When you’ve applied your Template to all required PDFs, go to the «Data Extracts» screen using the navigation button on the left side of the app. Click Export Data in the top-left tool bar. If you don’t have a subscription yet, you will need to begin a free trial. The trial lasts one month, and if you cancel during the trial period you will not proceed to a paid plan when the trial ends. In the export dialog, there are a number of options to control the rows/columns exported, and the file format. Choose the options you need, and click Export. In the file dialog, choose a location to save the output file. Open the file in Excel to review the extracted data.

  9. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

References

About This Article

Article SummaryX

1. Copy and paste the data from a PDF into an Excel document.
2. Set up a Docparser account and click Create Document Parser.
3. Create a name and select a template, then upload a PDF(s) and select Continue.
4. Follow the prompts that appear onscreen and create parsing rules as desired for your document.
5. Click the checkbox next to your document’s name and select Move to Parse Queue under Perform Action.
6. Wait for the file to finish re-parsing, refresh the page, click the document name, and select Excel Download.
7. On Adobe Acrobat Pro DC, select the text you would like to extract, then right-click it and choose Export Selection As….
8. Choose the XLSX format from the Save As Type list and click Save.

Did this summary help you?

Thanks to all authors for creating a page that has been read 15,664 times.

Is this article up to date?

Задача переноса данных из таблицы в PDF-файле на лист Microsoft Excel — это всегда «весело». Особенно если у вас нет дорогих программ распознавания типа FineReader или чего-то подобного. Прямое копирование обычно ни к чему хорошему не приводит, т.к. после вставки скопированных данных на лист, они, скорее всего, «слипнутся» в один столбец. Так что их потом придется кропотливо разделять с помощью инструмента Текст по столбцам с вкладки Данные (Data — Text to Columns).

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

Но все не так грустно, на самом деле :)

Если у вас Office 2013 или 2016, то за пару минут без дополнительных программ вполне можно реализовать перенос данных из PDF в Microsoft Excel. А помогут нам в этом Word и Power Query.

Для примера, давайте возьмем вот такой PDF-отчет с кучей текста, формул и таблиц с сайта Европейской Экономической Комиссии:

Исходный PDF

… и попробуем вытащить из него в Excel, скажем первую таблицу:

Нужная таблица в PDF

Поехали!

Шаг 1. Открываем PDF в Word

Почему-то мало кто знает, но начиная с 2013 года Microsoft Word научился открывать и распознавать PDF файлы (даже отсканированные, т.е. без текстового слоя!). Делается это совершенно стандартным образом: открываем Word, жмем Файл — Открыть (File — Open) и уточняем PDF-формат в выпадающем списке в правом нижнем углу окна.

Затем выбираем нужный нам PDF-файл и жмем Открыть (Open). Word сообщает нам, что собирается запустить распознавание этого документа в текст:

Запуск распознавания PDF в Word

Соглашаемся и через несколько секунд увидим наш PDF открытым для редактирования уже в Word:

Распознанный PDF в Word

Само-собой, у документа частично слетит дизайн, стили, шрифты, колонтитулы и т.п., но для нас это не важно — нам нужны только данные из таблиц. В принципе, на этом этапе уже возникает соблазн дальше просто скопировать таблицу из распознанного документа в Word и просто вставить ее в Excel. Иногда это срабатывает, но чаще приводит ко всевозможным искажениям данных — например числа могут превратиться в даты или остаться текстом, как в нашем случае, т.к. в PDF используется не российские разделители:

Искаженные данные

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

Этап 2. Сохраняем документ как веб-страницу

Чтобы потом загрузить полученные данные в Excel (через Power Query), наш документ в Word нужно сохранить в формате веб-страницы — этот формат является, в данном случае, неким общим знаменателем между Word’ом и Excel’ем.

Для этого идем в меню Файл — Сохранить как (File — Save As) или жмем клавишу F12 на клавиатуре и в открывшемся окне выбираем тип файла Веб-страница в одном файле (Webpage — Single file):

Сохраняем как веб-страницу

После сохранения должен получиться файл с расширением mhtml (если у вас в Проводнике видны расширения файлов).

Этап 3. Загружаем файл в Excel через Power Query

Можно открыть созданный MHTML-файл в Excel напрямую, но тогда мы получим, во-первых сразу все содержимое PDF вместе текстом и кучей ненужных таблиц, а, во-вторых, опять потеряем данные из-за неправильных разделителей. Поэтому импорт в Excel мы будем делать через надстройку Power Query. Это совершенно бесплатная надстройка, с помощью которой можно загружать в Excel данные практически из любых источников (файлов, папок, баз данных, ERP-систем) и всячески затем полученные данные трансформировать, придавая им нужную форму.

Если у вас Excel 2010-2013, то скачать Power Query можно с официального сайта Microsoft — после установки у вас появится вкладка Power Query. Если у вас Excel 2016 или новее, то качать ничего не нужно — весь функционал уже встроен в Excel по-умолчанию и находится на вкладке Данные (Data) в группе Загрузить и преобразовать (Get & Transform).

Так что идем либо на вкладку Данные, либо на вкладку Power Query и выбираем команду Получить данные или Создать запрос — Из файла — Из XML. Чтобы были видны не только XML-файлы — меняем в выпадающем списке в правом нижнем углу окна фильтры на Все файлы (All files) и указываем наш MHTML-файл:

Выбираем MHTML-файл для импорта в Excel

Обратите внимание, что импорт успешно не завершится, т.к. Power Query ждет от нас XML, а у нас, на самом деле, HTML-формат. Поэтому в следующем появившемся окне нужно будет щелкнуть правой кнопкой мыши по непонятному для Power Query файлу и уточнить его формат:

Уточняем настоящий формат файла

После этого файл будет корректно распознан и мы увидим список всех таблиц, которые в нем есть:

Выбираем таблицу для импорта

Посмотреть содержимое таблиц можно, если щелкать левой кнопкой мыши в белый фон (не в слово Table!) ячеек в столбце Data.

Когда нужная таблица определена, щелкните по зеленому слову Table — и вы «провалитесь» в её содержимое:

Нужная нам таблица

Останется проделать несколько простых действий, чтобы «причесать» ее содержимое, а именно:

  1. удалить ненужные столбцы (правой кнопкой мыши по заголовку столбца — Удалить)
  2. заменить точки на запятые (выделить столбцы, щелкнуть правой — Замена значений)
  3. удалить знаки равно в шапке (выделить столбцы, щелкнуть правой — Замена значений)
  4. удалить верхнюю строку (Главная — Удалить строки — Удаление верхних строк)
  5. удалить пустые строки (Главная — Удалить строки — Удаление пустых строк)
  6. поднять первую строку в шапку таблицы (Главная — Использовать первую строку в качестве заголовков)
  7. отфильтровать лишние данные с помощью фильтра

Когда таблица будет приведена в нормальный вид, ее можно выгрузить на лист командой Закрыть и загрузить (Close & Load) на Главной вкладке. И мы получим вот такую красоту, с которой уже можно работать:

Готовая таблица

Ссылки по теме

  • Трансформация столбца в таблицу с помощью Power Query
  • Разделение слипшегося текста по столбцам

PDF Извлечение-таблиц — это приложение для извлечения таблиц данных из PDF и сохранения результатов в форматах CSV, XLS, XLSX и других. С помощью нашего приложения вы можете получать любую статистику, финансы и другие данные в удобных форматах для обработки исходного документа. Извлекайте таблицы из PDF онлайн с Mac OS, Linux, Android, iOS. Если вы хотите извлекать таблицы данных программным способом, пожалуйста ознакомьтесь документацией .PDF.

Быстрый и легкий способ извлечения таблиц

Быстрый и легкий способ извлечения таблиц

Загрузите документ и нажмите кнопку «ИЗВЛЕЧЬ». Вы получите ZIP-архив с файлами извлеченных табличных данных моментально..

Извлекай табличные данные из любого места

Извлекай табличные данные из любого места

Работает со всех платформ, включая Windows, Mac, Android и iOS. Все файлы обрабатываются на наших серверах. Вам не требуется установка плагинов или программного обеспечения.

Качественное извлечения табличных данных

Качественное извлечения табличных данных

Все файлы обрабатываются с помощью Aspose API, которые используются многими компаниями из списка Fortune 100 в 114 странах..

Есть необходимость парсить данные из pdf документа. Сам документ состоит из таблицы с тремя колонками, перед таблицей немного ненужного текста. По сути нужна только таблица. Она на несколько страниц. В таблице по мимо текстовой информации есть гиперссылки, которые тоже нужно спарсить.

Чем можно эффективно выдернут все данные из этой таблицы, чтобы в последствии с простотой оперировать ими? Я думал на json. Но не знаю в верном направлении ли я смотрю.

Язык программирования не важен. Лишь бы была библиотека, которая может это реализовать.


  • Вопрос задан

    более двух лет назад

  • 1187 просмотров

Пригласить эксперта

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

Если pdf — не картинка, если в открытом adobe reader-ом файле pdf можно выделить и скопировать текст, то для того, чтобы вытащить оттуда таблицу, надо открыть pdf при помощи word. Затем из Word таблицу можно копипастить в excel.
Соответственно, автоматизировать этот процесс проще на основе MS office и VBA.

Чем можно эффективно выдернут все данные из этой таблицы, чтобы в последствии с простотой оперировать ими?

— если нужно извлекать отдельную таблицу, вроде только свой парсер писать (или на фриланс сходить), если просто извлечь весь текст, то popler-utils (можно постранично извлекать) использовать и потом уже парсите извлеченный текст, только нужно будет определить где начало таблицы где конец.


  • Показать ещё
    Загружается…

16 апр. 2023, в 16:39

80000 руб./за проект

16 апр. 2023, в 14:44

4500 руб./за проект

16 апр. 2023, в 13:46

1000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Парольная защита файла в word
  • Парольная защита документов ms word
  • Пароль с именем в excel
  • Пароль разрешения записи word
  • Пароль при сохранении excel