0

I'm trying to create HTML partials for each page from a PDF and retain or recreate the existing layout which is the same for each page. From what I've tried it seems best to recreate the layout using CSS but I need to add markup to the raw text.

I'm unable to split the PDF when exporting to HTML using Acrobat because there are no page headers or bookmarks. And Acrobat adds a crazy amount of markup to maintain the layout.

Next thing I tried was to split the PDF into single PDF files for each page and convert those using pdftotext with the -raw option which results in this example text:

MARCH 28
WORDS IN CAPS
(MAYBE 2 LINES)
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vivamus porttitor odio ac lorem euismod, vel malesuada quam
sollicitudin. Nam convallis tortor sit amet cursus posuere.
Nulla tempor, nulla in porta rhoncus, leo turpis aliquet dui,
at tempus orci magna sollicitudin nunc.
WORDS IN CAPS, p. 555
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer molestie ante eros, vel dapibus enim laoreet ut. Cras
molestie fermentum porta. Curabitur porttitor dui sed
ultricies sagittis. Duis at ligula tristique, sodales risus ac,
porta metus. Donec vitae fermentum metus. Vestibulum in urna
ante. Aliquam sed imperdiet leo. Morbi in orci id est posuere
dignissim.

Since each page has the same format I'm thinking I should be able to parse each one and add HTML tags as needed. For instance, the date gets wrapped in <p class="someclass">, the 2 lines containing WORDS IN CAPS get wrapped in h2 and the remaining 2 sections of lorem get wrapped in p tags, removing the linebreaks.

The best I've done so far is to use pdftotext with the -htmlmeta -layout options which preserves spacing but puts the content in <pre> tags. Then I can use python to extract the <pre> tag and its content from the extra html using:

from sys import argv
from pathlib import Path

start = '<pre>'
end = '</pre>'

for path in argv[1:]:
    text = Path(path).read_text()
    print(text[text.find(start) : text.find(end) + len(end)])

This gets me a usable partial but forces me to maintain the <pre> tags and doesn't provide the styling options I'd have if I could wrap parts of the content in HTML tags as described above.

I could probably use PHP and regex to handle one piece at a time but I'd prefer to do this with bash, python, sed, awk or something else. Trouble is I don't know which tool is best for the task.

What's the best tool to tackle this project?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.