Sometimes when drawing many paths on a PDF, for example when exporting thousands of lines from a CAD plot to a PDF, the process of drawing the paths can be slow.

The slowness is related to the process of adding the required commands to the content stream and reallocating memory each time a new path is drawn which slows the process down considerably.

However, it is possible to improve the performance here by adding the paths directly to the content stream yourself. You can do this on the generation side by creating the content stream manually — which is not as hard as it sounds. Basically you will be generating the line drawing commands manually and storing them into a large string and then using the SetContentStreamFromString function to insert the drawing commands into the PDF in one quick operation instead of thousands of calls.

You can use the GetContentStreamToString function to decompress the content stream for the drawing commands which you can then analyse. PDF commands are like postscript commands and you can manually create and optimize and generate the content stream yourself which will bypass most of the normal processing overhead. You can then use the content stream commands to add the stream back into the PDF in one simple operation.

He is some sample PDF commands that draws a single line. We just need to rinse and repeat to add more lines.

268.8066 424.4088 m = Move to
271.8255 420.2306 l = Line to
S = Stroke line

Here is a link to the PDF Specification that may help with more complex commands.

As you can see it should not be too difficult to generate. Using this approach you don’t need to know the PDF specification that well as you can use Debenu Quick PDF Library to create and manipulate the PDF and then you can generate the content stream efficiently with little overhead.

Here are most of the basic PDF commands that you will need – please consult the PDF manual for correct interpretation:

q = save state
m = moveto
l = lineto
re = rectangle
w = penwidth
RG = set fill color RGB
rg = set line color RGB
cm = transformation matrix

Using this approach is not very complex once you understand the concept and improves the speed considerably.