Search code examples
pdfpdf-generation

How to insert an image into PDF source code


I am trying to insert a JPEG image into PDF source code and I can't quite seem to figure out what might be going wrong? Text displays fine but images don't appear at all (and no error message displays in any PDF viewers).

I am assuming it has something to do with how I reference the image in my content stream, or maybe how the binary data is copied over, but I can't quite figure out exactly what is going wrong. I have provided what I believe to be the necessary minimum code below to show what I am trying to achieve.

...
3 0 obj
<<
/Type/Page
/Parent 2 0 R
/MediaBox [0 0 612 792]
/Contents 5 0 R
/Resources <<
    /Font <</F1 4 0 R>>
    /XObject <</I1 6 0 R>>
>>
>>
endobj
...
5 0 obj
<<
/Length 1
>>
stream
q
1 0 0 1 0 0 cm
/I1 Do
Q
BT/F1 10 Tf
100 632 Td(Hello world!)Tj
ET
endstream
endobj
6 0 obj
<<
/Type /XObject
/Subtype /Image
/Filter /DCTDecode
/Width 50
/Height 50
/ColorSpace /DeviceRGB
/BitsPerComponent 8
/Length 2291
>>
stream
[JPEG binary data here]
endstream
endobj
...

Solution

  • Generally your text encoded PDF is workable but as pointed out by @mkl in comments the image will be exceptionally hard to find and often Acrobat Reader may trigger a rebuild if some other text is not as expected. (your length of 5 0 obj << /Length 1 >> for the contents could be such a case, here it has been set as <</Length 95>>)

    Set a joint size and placement for the image here this will be 100 x 100 points at 650 from page baseline.

    100 0 0 100 100 650 cm
    /I1 Do
    

    This should be considered a minimal working example, without that trigger. enter image description here

    %PDF-1.7
    %ÄѧÎ
    1 0 obj
    <</Type/Catalog/Pages 2 0 R>>
    endobj
    
    2 0 obj
    <</Type/Pages/Count 1/Kids[3 0 R]>>
    endobj
    
    3 0 obj
    <</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]/CropBox[0 0 612 792]/Rotate 0/Resources<</XObject<</I1 5 0 R>>/Font<</F1 4 0 R>>>>/Contents 6 0 R>>
    endobj
    
    4 0 obj
    <</Type/Font/BaseFont/Helvetica/Subtype/Type1>>
    endobj
    
    5 0 obj
    <</Type/XObject/Subtype/Image/ColorSpace/DeviceRGB/BitsPerComponent 8/Width 50/Height 50/Length 2020/Filter/DCTDecode>>
    stream
    [image data ÿØÿà JFIF ....]
    endstream
    endobj
    
    6 0 obj
    <</Length 94>>
    stream
    q
    100 0 0 100 100 650 cm
    /I1 Do
    Q
    q
    BT
    /F1 10 Tf
    1 0 0 1 100 632 Tm
    (Hello world!) Tj
    ET
    Q
    q
    Q
    
    endstream
    endobj
    
    xref
    0 7
    0000000000 65536 f 
    0000000016 00000 n 
    0000000062 00000 n 
    0000000114 00000 n 
    0000000278 00000 n 
    0000000342 00000 n 
    0000002### 00000 n 
    
    trailer
    <</Size 7/Root 1 0 R>>
    startxref
    2xxx
    %%EOF
    

    where 2xxx will vary by image size and or location