PDFsharp - How to convert a cdata XML node to a PDF document?

174 Views Asked by At

The issue is that I'm trying to convert a cdata node from an XML document to a PDF document via PDFsharp. All I get is a damaged PDF document.

The is my test code:

Console.WriteLine("Read input file.");

String xmlFile = File.ReadAllText("input.xml");
XDocument xmlDoc = XDocument.Parse(xmlFile);
XElement node1Element = xmlDoc.Descendants("tekening").FirstOrDefault();
string cdataValue = node1Element.Element("tekening_data").Value;

Console.Write(cdataValue);
Console.WriteLine();

byte[] bytes = Encoding.UTF8.GetBytes(cdataValue);

Console.WriteLine("Create PDF from input file.");
using (PdfDocument InputDocument = PdfReader.Open(new MemoryStream(bytes), PdfDocumentOpenMode.Import))
{
    Console.WriteLine("Save as PDF file.");
    InputDocument.Save("output.pdf");
}

Console.WriteLine("Ready!");
Console.ReadLine();

The XML input:

                            <tekening>
                <tekening_data><![CDATA[%%Title: Platten-Skizze von AB: 20133/061123 Pos.: <0048|00> WB65
%%From: CNCBD
%%Creator: GAV Vers 5.2.21552
%%CreationDate: 2023-04-20 11:14:56
%Driver: PcsPrint 5.0.0
% *** Begin embedded object, PcsPrint 5.0.0 ***
/SaveMark_Embed save def
% save status
%%BeginProlog
%%
%% Standard prolog
%% (c) Copyright PCS Strakeljahn GmbH & Co. KG 2011
%%
/BIND {bind def} bind def /_SNAP {transform round exch round exch itransform} BIND /_DSNAP {dtransform round exch round exch
idtransform} BIND /LINE {_SNAP lineto} BIND /MOVE {_SNAP moveto} BIND /RLINE {_DSNAP rlineto} BIND 

.... snip ...

08WL6) CENTER GR
% <------------- END APL-Core
/DS {1.0000 mul} BIND GR
% Ende Platten-Skizze von AB: 20133/061123 Pos.: <0048|00> WB65
SaveMark_Embed restore
% *** End embedded object ***]]></tekening_data>
            </tekening>

I have tried to trim line ends, and removed a header that comes in with cdata XML node.

650 800 translate 180 rotate
<</Orientation 2>> setpagedevice
50 10 translate .95 .95 scale
1

There are 1 best solutions below

1
I liked the old Stack Overflow On

You have to open your XML with an XML reader. Then you create an empty PdfDocument in memory, add pages to the document as needed, write the data from the XML using DrawString as needed, and finally save the PDF document.

The PdfReader you are using can read PDF files only. It is not a magic "convert any file type to PDF" converter.