Flatten FDF / XFDF forms to PDF in PHP with utf-8 characters

Viewed 13874

My scenario:

  • A PDF template with formfields: template.pdf
  • An XFDF file that contains the data to be filled in: fieldData.xfdf

Now I need to have these to files combined & flattened. pdftk does the job easily within php:

exec("pdftk template.pdf fill_form fieldData.xfdf output flatFile.pdf flatten");

Unfortunately this does not work with full utf-8 support. For example: Cyrillic and greek letters get scrambled. I used Arial for this, with an unicode character set.

  • How can I accomplish to flatten my unicode files?
  • Is there any other pdf tool that offers unicode support?
  • Does pdftk have an unicode switch that I am missing?

EDIT 1: As this question has not been solved for more then 9 month, I decided to start a bounty for it. In case there are options to sponsor a feature or a bugfix in pdftk, I'd be glad to donate.

EDIT 2: I am not working on this project anymore, so I cannot verify new answers. If anyone has a similar problem, I am glad if they can respond in my favour.

13 Answers

While pdftk doesn't appear to support UTF-8 in the FDF file, I found that with

iconv -f utf-8 -t ISO_8859-1

in the pipeline converting that FDF file to ISO-Latin-1, then at least those characters that are in the Latin-1 code page will still be represented properly.

You can introduce utf-8 characters by giving their unicode code in octal with \ddd

I have managed to make it work with pdftk by creating a xfdf file with utf-8 encoding.

it took several tried but what make it work as exepcted was to add 'need_appearances'

here is an example:

pdftk source.pdf fill_form data.xfdf output output.pdf need_appearances

I have been solving this issue for a long time, and finally I have found the solution!

so, let's start.

  1. download and install the latest version of pdftk
# PDFTK
RUN apk add openjdk8 \
    && cd /tmp \
    && wget https://gitlab.com/pdftk-java/pdftk/-/jobs/1507074845/artifacts/raw/build/libs/pdftk-all.jar \
    && mv pdftk-all.jar pdftk.jar \
    && echo '#!/usr/bin/env bash' > pdftk \
    && echo 'java -jar "$0.jar" "$@"' >> pdftk \
    && chmod 775 pdftk* \
    && mv pdftk* /usr/local/bin \
    && pdftk -version
  1. Open your PDF Form in Adobe Acrobat Reader and look at field options, you need to detect the font, for example Helvetica, download this font.
  2. Fill the form with flatten option
/usr/local/bin/pdftk A=form.pdf fill_form xfdf.xml output out.pdf drop_xfa need_appearances flatten replacement_font /path/to/font/HelveticaRegular.ttf

xfdf.xml example:

<?xml version="1.0" encoding="UTF-8"?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
    <fields>
        <field name="Check Box 136">
            <value>Your value | Значение (Cyrillic)</value>
        </field>
    </fields>
</xfdf>

Enjoy :)

Related