Search code examples
pdfcolor-space

How do I define a colorspace and set it on images in a PDF?


An application that I work on programmatically generates a PDF. I was asked to add the ability to set the colorspace of the images, which should all be the same. Currently, my code generates the colorspace as the following:

3 0 obj
<<
/N 3
/Alternate /DeviceRGB
/Length 284
/Filter [/FlateDecode]
>>
stream
8c``2ptqre``ÈÍ+)
rwRˆˆŒR`¿ÀÀÁÀÍ Ì`Ì`˜\\ààà yùy© |»ÆÀ¢/ë‚Ì”Ǹ’ŠJ€ô 6JI-Nf``4 ²³ËK
€âŒs€l‘¤l0{ˆ]äd²ùÒ!ì+ v„ýÄ.zÈþRŸf3q€Í°e@ì’Ô
½Îù•E™é%
F
Ž)ùI©
Á•Å%©¹Å
žyÉùEùE‰%©)@µ÷ D!(Ä4---4Iô7A Šës 8|ÅÎ Ä ¹´¨Êdd2&ÌG˜1G‚Á)Ë„˜I/Ãþ©15C}†}s ïPo
endstream
endobj
4 0 obj
[/ICCBased 3 0 R]
endobj

This works, in and of that the PDF will load. However, when I try to set that colorspace on an image, such as the following:

23 0 obj
<<
/Type /XObject 
/Subtype /Image 
/Name /I5 
/Length 2995953 
/Width 3675 
/Height 3675 
/Filter /DCTDecode 
/ColorSpace 4 0 R
/BitsPerComponent 8
>>
stream

Image data not included here for brevity

endstream
endobj

This looks valid based on scanning another PDF with an image. If I don't try to replace the Colorspace, but instead use "/Colorspace /DeviceRGB", the PDF loads fine.

I know I'm probably missing something important here, but I can't figure out what.

ICC profile being used

Bad PDF


Solution

  • The problem was with the cross reference index, which was missing the entry for 4 0 R the [/ICCBased 3 0 R] object.

    I noticed the problem when opening the PDF with xpdf, which gave the error: Internal Error: xref num 25 not found but needed, try to reconstruct.

    From there, I manually cross-checked the cross reference table against the actual objects using a text editor to locate the missing object.

    The xref table needed a couple of small edits, as follows:

    xref 0 26 %% <-- was 0 25 0000000000 65535 f 0000000009 00000 n 0000000201 00000 n 0000000253 00000 n 0000000638 00000 n %% <-- added this line 0000000671 00000 n 0000000764 00000 n 0000000928 00000 n 0000001031 00000 n 0000001195 00000 n 0000001298 00000 n 0000001464 00000 n 0000001568 00000 n 0000001734 00000 n 0000001838 00000 n 0000002004 00000 n 0000002108 00000 n 0000002274 00000 n 0000002378 00000 n 0008538650 00000 n 0012148952 00000 n 0020386142 00000 n 0025352962 00000 n 0027568145 00000 n 0030564286 00000 n 0030564334 00000 n trailer

    PDF then opened and displayed normally, using xpdf.