Search code examples
pdfpdf-generationgradientzend-pdf

PDF color gradient not rendering same (or at all) in different viewers


I am trying to create a linear color gradient in PDF. After some effort, I was able to render a rectangle filled with gradient in Chrome, however Mozilla only renders a black rectangle and Acrobat reader is completely blank.

I am pretty sure Chrome interpreted the source code wrong but I can't find what is wrong with and how to render the gradient in Acrobat reader.

Please consider the source code below. Can anybody see what is wrong with it? (Yes, I am well aware there is an empty /Bounds attribute in the function but I have tested the code without it with no effect.)

In case you are wondering, the code is generated using Zend PDF library for PHP with my custom methods for the gradient. It is no longer maintained but it is a tool we use at my work so I am stuck with it for now. That is also the reason why PDF is only version 1.4.

Here is the complete source code

%PDF-1.4 %
1 0 obj 
<</Type /Catalog /Version /1.4 /Pages 2 0 R /Names 5 0 R >>
endobj
2 0 obj 
<</Type /Pages /Kids [8 0 R ] /Count 1 >>
endobj
3 0 obj 
[]
endobj
4 0 obj 
<</Names 3 0 R >>
endobj
5 0 obj 
<</Dests 7 0 R >>
endobj
6 0 obj 
[]
endobj
7 0 obj 
<</Names 6 0 R >>
endobj
8 0 obj 
<</Type /Page /LastModified (D:20240226231224+01'00') /Resources <</Pattern <</P1 10 0 R >> /ProcSet [/PDF ] >> /MediaBox [0 0 595 842 ] 
/Contents [9 0 R ] /Parent 2 0 R >>
endobj
9 0 obj 
<</Length 41 >>
stream
/Pattern sc
/P1 scn
30 300 370 450 re
 f

endstream
endobj
10 0 obj 
<</Type /Pattern 
/PatternType 2 
/Shading 
    <</ShadingType 2 
    /ColorSpace /DeviceRGB 
    /Domain [0 1 ] 
    /Coords [30 750 30 300 ] 
    /Function 
        <</FunctionType 3 
        /Domain [0 1 ] 
        /Bounds [] 
        /Encode [1 0 ] 
        /Functions [
            <</FunctionType 2 
            /Domain [0 1 ] 
            /C0 [0 0.733 0 ] 
            /C1 [0 0 0 ] 
            /N 1 
            >> 
        ] 
        >> 
    /Extend [true true ] 
    >> 
/Matrix [1 0 0 1 0 0 ] 
>>
endobj
xref
0 11 
0000000000 65535 f 
0000000015 00000 n 
0000000091 00000 n 
0000000149 00000 n 
0000000168 00000 n 
0000000202 00000 n 
0000000236 00000 n 
0000000255 00000 n 
0000000289 00000 n 
0000000479 00000 n 
0000000570 00000 n 
trailer
<</ID [<38363664323065366363363538333838> <39323837366165306561666364386532> ] /Size 11 /Root 1 0 R >>
startxref
917
%%EOF

And here is the final file for download.


Solution

  • The page content stream is incorrect, it should be:

    /Pattern cs % set colorspace for non-stroking operations
    

    You currently have:

    /Pattern sc % set fill color which is incorrect as the scn operator will set it
    

    I assume this the result you want: enter image description here