0

I am able to create a word doc using the code below.

Question: how do i create a pdf instead of word doc?

Code

using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, tdindb.TDCode + "-test.doc")))
        {
            string html = string.Format("<html>{0}</html>", sbHtml);

            outputFile.WriteLine(html);
        }

        string FileLocation = docPath + "\\" + tdindb.TDCode + "-test.doc";


        byte[] fileBytes = System.IO.File.ReadAllBytes(FileLocation);
        string fileName = Path.GetFileName(FileLocation);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

Thank you

Beginner
  • 11
  • 4
  • 4
    *"I am able to create a word doc using the code below."* - No. You create a html file which you save with a name with the 'doc' extension. That doesn't make the file a doc file, it still is a html file. As MS Word can also open html files, you might not have noticed the differences. – mkl Aug 18 '21 at 10:30
  • 1
    I encourage you to read on html, doc(x) and pdf formats to see the basics of their structure. They are completely different languages and they need to be translated. It's just like renaming a code.cs file to code.py file will not make it magially become valid python code. File extension is just a little helper to determine how to open a file, it has nothing to do with the actual content of the file, which is regulated by the format used. – SnowGroomer Aug 18 '21 at 10:40

2 Answers2

0

You need to use one of PDF creating libraries. I tried to use iText , IronPDF, and PDFFlow. All of them create PDF documents from scratch.

But PDFFlow was better for my case because i needed automatic page creation and multi-page spread table)

This is how to create a simple PDF file in C#:

{
var DocumentBuilder.New()  
  .AddSection()  
    .AddParagraphToSection("your text goes here!") 
  .ToSection()
.ToDocument()  
   .Build("Result.PDF"); 
 }

feel free to ask me if you need more help.

0

Converting a Word document to HTML has been answered here before. The linked example is the first result of many on this site.

Once you have your HTML, to create a PDF you need to use a PDF creation library. For this example we will use IronPDF which requires just 3 lines of code:

string html = string.Format("<html>{0}</html>", sbHtml);
var renderer = new IronPdf.ChromePdfRenderer();
// Save PDF file to BinaryData
renderer.RenderHtmlAsPdf(html).BinaryData;

// Save file to location
renderer.RenderHtmlAsPdf(html).SaveAs("output.pdf");
darren
  • 475
  • 4
  • 15
  • 2
    works for me! reasonable beginner question about file format conversion in .NET and reasonable answer that worked when i tried it. I used Mammoth.NET + IronPDF. – Stephanie Sep 23 '21 at 04:18