Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Insert PDF as Base64 into XML, then Extract back to PDF File

See more XML Examples

Demonstrates how to insert any file into XML using base64 encoding, and then extract back to the original file. This example embeds a PDF in the XML, but the type of file does not matter. It can be any type of file.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.BinData,
  Chilkat.Xml;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  bd: TBinData;
  xml: TXml;
  bd2: TBinData;

begin
  success := False;

  //  Load our PDF file.
  bd := TBinData.Create;
  success := bd.LoadFile('qa_data/helloWorld.pdf');
  if (success <> True) then
    begin
      WriteLn('Failed to load PDF file.');
      Exit;
    end;

  //  Load the following XML:
  //  
  //  <?xml version="1.0" encoding="utf-8" ?>
  //  <something>
  //      <xyz>
  //          <abc123>A base64 encoded PDF file will be inserted under this node.</abc123>
  //      </xyz>
  //  </something>

  xml := TXml.Create;
  success := xml.LoadXmlFile('qa_data/xml/xmlToContainPdf.xml');
  if (success <> True) then
    begin
      WriteLn('Failed to load XML file.');
      Exit;
    end;

  //  Insert the PDF into the XML.
  xml.NewChild2('xyz|pdfData',bd.GetEncoded('base64'));

  //  Show the new XML:
  WriteLn(xml.GetXml());

  //  The XML now looks like this:
  //  <?xml version="1.0" encoding="utf-8" ?>
  //  <something>
  //      <xyz>
  //          <abc123>A base64 encoded PDF file will be inserted under this node.</abc123>
  //          <pdfData>JVBERi0xL ... UlRU9GCg==</pdfData>
  //      </xyz>
  //  </something>

  //  To extract the PDF data out and restore the PDF file:
  bd2 := TBinData.Create;
  success := bd2.AppendEncoded(xml.GetChildContent('xyz|pdfData'),'base64');
  success := bd2.WriteFile('qa_output/helloWorld.pdf');

  WriteLn('Success.');


  bd.Free;
  xml.Free;
  bd2.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.