Itextsharp is a popular PDF library that we can use to create, modify, or perform additional actions on PDF files. This article describes how to convert a text file into a PDF during the upload process.
Basic work
Before we start, we need to download itextsharp from this URL. In addition, you can use NuGet package Manager to download it from NuGet to your project's solution. This is explained by the screen below.
Code
For simplicity, I designed a webform with an upload control and a button. The HTML code is as follows:
<! DOCTYPE html> 1.
The background code is as follows:
1.protected void Btnupload_click (object sender, EventArgs e) 2. {3.//Check that upload control had file 4. if (FU. HasFile) 5. {6.//Get the Posted File 7. Httppostedfile pf = Fu. PostedFile; 8. Int32 FileLen; 9.//Get The Posted file Content Length 10. FileLen = Fu. Postedfile.contentlength; One.//Create a byte array with content length 12. byte[] Input = new Byte[filelen]; //Create Stream 14. System.IO.Stream MyStream; .//Get the stream of uploaded file 16. MyStream = Fu. Filecontent; //Read from the stream 18. Mystream.read (Input, 0, FileLen); .//Create a Document 20. Document doc = new document (); //Create PDF File and create a writer on it 22.PDFWriter writer = pdfwriter.getinstance (doc, New FileStream (string. Concat (Server.MapPath ("~/pdf/pdfsample"), ". Pdf"), FileMode.Create)); //Open the document 24. Doc. Open (); //Add The text file contents 26. Doc. ADD (New Paragraph (System.Text.Encoding.Default.GetString (Input))); .//Close the document 28. Doc. Close (); 29.} 30. }
When you run the application, it displays an upload control and an upload button. After the conversion, the PDF file is stored in the PDF folder. Of course, before we run the application, we need to create a folder named "PDF" under the solution.
Output results
Asp. NET to convert text files to PDF in the upload process