PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Convert txt file to pdf
https://forum.pdfsharp.net/viewtopic.php?f=2&t=3740
Page 1 of 1

Author:  Chiliyago [ Sun Mar 11, 2018 4:20 pm ]
Post subject:  Convert txt file to pdf

I have a project that requires reading in a number of txt files of various lengths and converting them to pdf. What is the most straight forward way to do that? I have varying page sizes I have to deal so I want to just read in my text and create a PdfDocument. Is there a way to just have the DrawString auto size and add pages automatically or must I do all those calculations to keep adding pages and rectagles? Are there more samples our there somewhere that can show how to handle multiple unknown pages?

Thanks

Quote:
var fileTxt =
System.IO.File.ReadAllText(@"K:\SOMEFILE.TXT",
Encoding.UTF8);



// Set font encoding to unicode
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode);
XFont font = new XFont("Courier New", 6, XFontStyle.Regular, options);


// Create new document
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();

XGraphics gfx = XGraphics.FromPdfPage(page);


XTextFormatter tf = new XTextFormatter(gfx);
tf.Alignment = XParagraphAlignment.Left;

tf.DrawString(fileTxt, font, XBrushes.Black,
new XRect(20, 20, page.Width-20, 300), XStringFormats.TopLeft);

Author:  TH-Soft [ Sun Mar 11, 2018 5:00 pm ]
Post subject:  Re: Convert txt file to pdf

I would most likely use MigraDoc's Document class and add each line of the TXT file using AddParagraph.
You get the page breaks for free.
http://pdfsharp.net/wiki/HelloMigraDoc-sample.ashx

Another option is the XTextFormatter class or the XTextFormatterEx family of classes - but you still have to add the page breaks and take care of page margins.
http://pdfsharp.net/wiki/TextLayout-sample.ashx
viewtopic.php?p=9372#p9372

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/