Как установить положение оглавления при использовании wkhtmltopdf - PullRequest
4 голосов
/ 10 мая 2011

Я использую wkhtmltopdf для генерации PDF из HTML-страниц.

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

Ответы [ 2 ]

6 голосов
/ 10 мая 2011

В wkhtmltopdf есть параметр --xsl-style-sheet (file), подробно описанный в расширенной командной строке --help (или -H).

A table of content can be added to the document by adding a toc object to
the command line. For example:  

  wkhtmltopdf toc http://doc.trolltech.com/4.6/qstring.html qstring.pdf

The table of content is generated based on the H tags in the input
documents. First a XML document is generated, then it is converted to
HTML using XSLT.

The generated XML document can be viewed by dumping it to a file using
the --dump-outline switch. For example:

  wkhtmltopdf --dump-outline toc.xml http://doc.trolltech.com/4.6/qstring.html qstring.pdf

The XSLT document can be specified using the --xsl-style-sheet switch.
For example:

  wkhtmltopdf toc --xsl-style-sheet my.xsl http://doc.trolltech.com/4.6/qstring.html qstring.pdf

The --dump-default-toc-xsl switch can be used to dump the default
XSLT style sheet to stdout. This is a good start for writing your
own style sheet

  wkhtmltopdf --dump-default-toc-xsl

The XML document is in the namespace 
  http://code.google.com/p/wkhtmltopdf/outline

it has a root node called "outline" which contains a number of
"item" nodes. An item can contain any number of item. These are the
outline subsections to the section the item represents. A item node
has the following attributes:

 - "title" the name of the section
 - "page" the page number the section occurs on
 - "link" a URL that links to the section.
 - "backLink" the name of the anchor the the section will link back to.

The remaining TOC options only affect the default style sheet
so they will not work when specifying a custom style sheet.

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

3 голосов
/ 01 марта 2012

Если вы хотите, вы даже можете сделать свой индивидуальный TOC, используя HTML-файл.например;Если вы хотите создать оглавление с именами имен файлов html, которые будут использоваться при создании PDF (обратите внимание, что для этого вы должны знать имена заранее), тогда вы можете сделать это, передав HTML-файл, например user_toc.html.В этих файлах вы можете поместить все ваши заголовки / css и т. Д. И сделать заполнитель для имени файла.Эти файлы необходимо проанализировать с помощью кода на стороне сервера, который должен заполнить имя файла в заполнителе.Теперь измененный файл можно использовать для оглавления.

Пример кода в Perl:

    my $TOCPage = "user_toc.html";
    my $file1 = "Testfile1.html";
    my $file2 = "Testfile2.html";
    my $toc_file_lines;

    # Open the user TOC for parsing and write in a buffer
    open(FILE, $TOCPage);
    read(FILE, $toc_file_lines, -s $TOCPage);
    close(FILE);

    # Substitute the placeholder with actual file name
    $toc_file_lines =~ s/$file_name_placeholder/$file1/;
    # Open the same file again and write back the buffer
    open(FILE, ">".$TOCPage);
    print FILE $toc_file_lines;
    close(FILE);

    # Linux path for wkhtmltopdf installation
    my $wkhtmltopdf_path = '/usr/bin/wkhtmltopdf-i386';  
    my $command = "$wkhtmltopdf_path --margin-top 20mm --margin-bottom 15mm 
                                    --margin-left 15mm --margin-right 15mm 
                                    $TOCPage $file1 $file2 $pdf_manual_name"; 
   `$command 2>&1`;

Более того, вы можете добавить много другой информации в TOC, например, номер главы / общая страница в главе и т. Д.помогает.

...