Search code examples
pdf-generation

Trying to do shading in a PDF


I'm am using a few PDF creation libraries and tweaking them to do more. I'm currently trying to do shading on a shape. I can't seem to be able to get it to work after reading lots of examples. This is currently a simple PDF I've created that should have a shaded square but is blank. Can anyone tell me why?

%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Length 42>>
stream
2 J
0.57 w
10 10 50 50 re
q
W n
/Sh1 sh
Q

endstream
endobj
1 0 obj
<</Type /Pages
/Kids [3 0 R ]
/Count 1
/MediaBox [0 0 595.28 841.89]
>>
endobj
5 0 obj
<<
/FunctionType 2
/Range [0.0 1.0]
/Domain [0.0 1.0]
/C0 [0.1]
/C1 [0.0705882]
/N 1
>>
endobj
6 0 obj
<<
/ShadingType 2
/ColorSpace /DeviceRGB
/Coords [15.000 15.000 45.000 30.000]
/Function 5 0 R
/Domain [0 1] 
/Extend [true true] 
>>
endobj
2 0 obj
<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
/Font <<
>>
>>
endobj
/Shading <<
/Sh1 6 0 R
>>
7 0 obj
<<
/Producer (New Affinity xxxxxxxxxxxxxxxxxx [www.newaffinity.com])
/CreationDate (D:20211113101858)
>>
endobj
8 0 obj
<<
/Type /Catalog
/Pages 1 0 R
/OpenAction [3 0 R /FitH null]
/PageLayout /OneColumn
>>
endobj
xref
0 9
0000000000 65535 f 
0000000177 00000 n 
0000000516 00000 n 
0000000009 00000 n 
0000000087 00000 n 
0000000264 00000 n 
0000000367 00000 n 
0000000620 00000 n 
0000000740 00000 n 
trailer
<<
/Size 9
/Root 8 0 R
/Info 7 0 R
>>
startxref
843
%%EOF

Solution

  • The PDF file is incorrect, the /Shading resource dictionary is outside the object.

    2 0 obj
    <</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
    /Font <<
    >>
    >>
    endobj
    /Shading <<
    /Sh1 6 0 R  
    >>
    

    Put it inside the object:

    2 0 obj
    <<
      /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
      /Font <<  >>
      /Shading << /Sh1 6 0 R >>
    >>
    endobj
    

    set shading colorspace to /DeviceGray, set /C0 [0], set /C1 [1] (for demo to increase visibility) and the shading will be displayed.
    If you want to go with /DeviceRGB then /C0 and /C1 arrays must have 3 elements and /Range must have 6 elements.