summaryrefslogtreecommitdiff
path: root/tests/test_formxobject.py
blob: 7e252c92a0effb358106c4d1d2ac23b146555cb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import pytest

from pikepdf import Dictionary, Name, Object, Pdf, Stream

# pylint: disable=e1137


def test_create_form_xobjects(outdir):
    pdf = Pdf.new()

    font = pdf.make_indirect(
        Object.parse(
            b"""
            <<
                /Type /Font
                /Subtype /Type1
                /Name /F1
                /BaseFont /Helvetica
                /Encoding /WinAnsiEncoding
            >>
        """
        )
    )

    width, height = 100, 100
    image_data = b"\xff\x7f\x00" * (width * height)

    image = Stream(pdf, image_data)
    image.stream_dict = Object.parse(
        """
            <<
                /Type /XObject
                /Subtype /Image
                /ColorSpace /DeviceRGB
                /BitsPerComponent 8
                /Width 100
                /Height 100
            >>
    """
    )
    xobj_image = Dictionary({'/Im1': image})

    form_xobj_res = Dictionary({'/XObject': xobj_image})
    form_xobj = Stream(
        pdf,
        b"""
        /Im1 Do
    """,
    )
    form_xobj['/Type'] = Name('/XObject')
    form_xobj['/Subtype'] = Name('/Form')
    form_xobj['/FormType'] = 1
    form_xobj['/Matrix'] = [1, 0, 0, 1, 0, 0]
    form_xobj['/BBox'] = [0, 0, 1, 1]
    form_xobj['/Resources'] = form_xobj_res

    rfont = {'/F1': font}

    resources = {'/Font': rfont, '/XObject': {'/Form1': form_xobj}}

    mediabox = [0, 0, 612, 792]

    stream = b"""
        BT /F1 24 Tf 72 720 Td (Hi there) Tj ET
        q 144 0 0 144 234 324 cm /Form1 Do Q
        q 72 0 0 72 378 180 cm /Form1 Do Q
        """

    contents = Stream(pdf, stream)

    page = pdf.make_indirect(
        {
            '/Type': Name('/Page'),
            '/MediaBox': mediabox,
            '/Contents': contents,
            '/Resources': resources,
        }
    )

    pdf.pages.append(page)
    pdf.save(outdir / 'formxobj.pdf')