From 66d28b0c86254f8e7ef15dda8df146a71843bb65 Mon Sep 17 00:00:00 2001 From: Youen Date: Thu, 27 Apr 2023 18:38:05 +0200 Subject: [PATCH] Added code to generate PDF --- pdftoc-to-latex | 72 ++++++++++++++++++++++++++++++++++++++++++++ src/data/document.py | 15 +++++++++ 2 files changed, 87 insertions(+) create mode 100755 pdftoc-to-latex diff --git a/pdftoc-to-latex b/pdftoc-to-latex new file mode 100755 index 0000000..314f01c --- /dev/null +++ b/pdftoc-to-latex @@ -0,0 +1,72 @@ +#!/usr/bin/perl + +# Script taken from https://gitlab.com/derobert/random-toys/blob/master/pdf/pdftoc-to-latex +# Manually adapt for sphinxdoc generated pdf +use 5.024; +use strict; +use warnings qw(all); +use IPC::Run3; +use LaTeX::Encode; +use Encode qw(decode); + +my @levels + = qw(chapter section subsection subsubsection paragraph subparagraph); +my @counters; + +my ($data_enc, $data); +run3 ['pdftk', $ARGV[0], 'dump_data_utf8'], undef, \$data_enc; +$data = decode('UTF-8', $data_enc, Encode::FB_CROAK); + +my @latex_bm; + +my $bm; +foreach (split(/\n/, $data)) { + /^Bookmark/ or next; + if (/^BookmarkBegin$/) { + add_latex_bm($bm) if $bm; + $bm = {}; + } elsif (/^BookmarkLevel: (\d+)$/a) { + ++$counters[$1 - 1]; + $#counters = $1 - 1; + $bm->{number} = join(q{.}, @counters); + $bm->{level} = $1 - 1; + } elsif (/^BookmarkTitle: (.+)$/) { + # In Sphinx title include a utf-8 icon of a link, so remove it + my $title = substr($1, 0, -1); + $bm->{title} = latex_encode($title); + } elsif (/^BookmarkPageNumber: (\d+)$/a) { + $bm->{page} = $1; + } else { + die "Unknown Bookmark tag in $_\n"; + } +} +add_latex_bm($bm) if $bm; + +print < 2 + if ($bm->{level} == 0 || $bm->{level} > 2) { + return; + } + # Make sections become chapters + my $level = $levels[$bm->{level} - 1]; + # Remove the first number because it refers to the root title (ie always 1.X) + my $number = substr($bm->{number}, 2); + my $title = $bm->{title}; + my $page = $bm->{page} + 2; + + push @latex_bm, < "' + self.doc_path + '/build/weasyprint/toc.tex"']) + cmd.append(['sh', '-c', 'pdflatex -interaction nonstopmode -output-directory="' + self.doc_path + '/build/weasyprint" "' + self.doc_path + '/build/weasyprint/toc.tex" || echo OK']) + cmd.append(['pdftk', 'A=' + self.doc_path + '/build/weasyprint/index.pdf', 'B=' + self.doc_path + '/build/weasyprint/toc.pdf', 'cat', 'A1', 'B', 'A2-end', 'output', self.doc_path + '/build/weasyprint/vheliotech.pdf']) + #cmd.append(['rm', self.doc_path + '/build/weasyprint/index.pdf', self.doc_path + '/build/weasyprint/toc.tex', self.doc_path + '/build/weasyprint/toc.pdf', self.doc_path + '/build/weasyprint/GuidedemontageVheliotech.pdf']) + + # Copy the generated PDF file to the HTML directory, so that it is accessible for download by users + cmd.append(['cp', self.doc_path + '/build/weasyprint/vheliotech.pdf', self.doc_path + '/build/html/vheliotech.pdf']) + task = ProcessTask(cmd, cwd = self.doc_path + "/repo") task.start()