Home > Code > C# > How To generate PDF using C# code

How To generate PDF using C# code

by SARNAM SINGH   on Jun 27, 2016   Category: C#   |  Views: 525    |  Points: 25   |  Silver 


//Adding Namespace
using Word = Microsoft.Office.Interop.Word;

Word.Application wordApp = null;
Word.Document wordDocument = null;
object missing = Type.Missing;
object outputFileName = String.Format("{0}\\{1}.pdf", Server.MapPath("~/TemplateFile"), Guid.NewGuid().ToString());
object saveFileFormat = Word.WdSaveFormat.wdFormatPDF;
try
{
wordApp = new Word.Application();
wordApp.Visible = false;
wordDocument = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Word.Paragraph headerParagraph = wordDocument.Paragraphs.Add(ref missing);
headerParagraph.Range.Text = "Your text goes here";
headerParagraph.Range.Font.Name = "Arial";
headerParagraph.Range.Font.Size = 16;
headerParagraph.Range.Font.Bold = 5;
headerParagraph.Range.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
headerParagraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
headerParagraph.Range.InsertParagraphAfter();
//adding table
object AutoFit = true;
object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
Word.Table tbl= wordDocument.Tables.Add(headerParagraph.Range, 6, 4, ref missing, AutoFitBehavior);
tblClaimInformation.Borders.Enable = 1;
// add data to EACH Table cell
tbl.Cell(rowNumber, i).Range.Text

//temporary saving word file not necessary if u dont want
object docFormat = Word.WdSaveFormat.wdFormatDocumentDefault;
object docFile = ((string)outputFileName).Replace(".pdf", ".docx");
wordDocument.SaveAs(ref docFile,
ref docFormat, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
wordDocument.SaveAs(ref outputFileName,
ref saveFileFormat, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
}
}
catch (Exception ex)
{

throw;
}
finally
{
wordDocument.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
string fileName = (string)outputFileName;
if (System.IO.File.Exists(fileName.Replace(".pdf", ".docx")))
{
System.IO.File.Delete(fileName.Replace(".pdf", ".docx"));

}
}


Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts