Search code examples
c#winformspdfpdf-generation

Correct PDF code structure in PDF writer class for C# application


I have written a simple PDF writer class for a Windows Forms C# application, but I am having some issues with the PDF output.

The application creates and writes to the file successfully, however when I open the file in a PDF viewer, only the first line (Hello world!) is shown, and the next two lines which should be in the document are not visible.

When I open the file in notepad, this is the output:

%PDF-1.7
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<< /Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj
3 0 obj
<< /Type /Page
/Parent 2 0 R
/Resources << >>
/Contents 4 0 R
/MediaBox [0 0 612 792]
>>
endobj
4 0 obj
<< /Length 300 >>
stream
BT
/Arial 12 Tf
50 700 Td
(Hello world!) Tj
50 680 Td
(01/05/2024 08:50:34) Tj
50 660 Td
(29 April 2024 - 01 May 2024) Tj
ET
endstream
endobj
<<
/Type /Metadata
/Subtype /XML
/Length 100
>>
stream
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
</x:xmpmeta>
<?xpacket end="w"?>
endstream
endobj
<< /MarkInfo << /Marked true >> >>
endobj
<< /Type /StructTreeRoot >>
endobj
xref
0 5
0000000000 65535 f 
0000000009 00000 n 
0000000055 00000 n 
0000000108 00000 n 
0000000197 00000 n 
trailer
<< /Root 1 0 R
/Metadata 5 0 R
/MarkInfo 6 0 R
/StructTreeRoot 7 0 R
/Size 5
>>
startxref
254
%%EOF

Why is only the first line being shown? Is there an error in my PDF code structure? Or is it an issue with the PDF viewer?

Please note, I don't want to use an external PDF writer library for this project.


Solution

  • The Td operator work this way: Td operator Your first Td operator moves the drawing position to (50, 700) but the second one moves it to (100, 1380) which is outside the page visible area.

    This fix

    BT
    /Arial 12 Tf
    50 700 Td
    (Hello world!) Tj
    0 -20 Td
    (01/05/2024 08:50:34) Tj
    0 -20 Td
    (29 April 2024 - 01 May 2024) Tj
    ET
    

    will generate this output: PDFXplorer

    Also your PDF file has several problems: the length of the page content stream is incorrect and there is no /Arial font in /Resources dictionary. These errors