Convert blank .txt file to PDF in C# - c#

I am converting a .txt to .pdf in c#. This works fine if the .txt file is not blank. if it is, it threw an error of "The document has no pages".
The pdf gets generated but threw an error of "There was an error opening this document. The file is damaged and could not be repaired" when opening a pdf file.
Code is seen below
public void converttxttoPDF(string sourcePath, string destPath)
{
try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
string filename = Path.GetFileNameWithoutExtension(sourcePath);
System.IO.StreamReader myFile = new System.IO.StreamReader(sourcePath);
string myString = myFile.ReadToEnd();
myFile.Close();
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
document.Open();
document.Add(new iTextSharp.text.Paragraph(myString));
document.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
let me know if any info needed.
thanks

You need to add some content to the pdf. So try this:
myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));

You need to convince iText that there IS something on that page.
Two Methods:
Be explicit. writer.setPageEmpty(false);
Trick it (which is what Darin suggests). writer.getDirectContent().setLiteral(" ");

Related

Convert bytes to PDF File

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
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.
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");

Convert HTML to PDF using iText with special char fail

I'm facing a problem by using iText and XMLWorkerHelper for a specific case. I generate multiple PDF files with multiple pages without problem but sometimes, an error occur with special characters.
I tested my template and it's not a problem with my HTML, even if the exception say :
Exception thrown: 'iTextSharp.tool.xml.exceptions.RuntimeWorkerException' in itextsharp.xmlworker.dll
Additional information: Invalid nested tag tr found, expected closing tag td.
This error is due to the character : & which is added into my template.
<td>Launch C&O</td>
I don't exactly know how to resolve this error, is it an encoding error ? Should I specify an encoding mode when I create the PDF ?
This is the code which create a PDF :
public async Task Generate(Stream stream, List<string> contentPages)
{
try
{
int cpt = 1;
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
foreach (string pdfContentPage in contentPages)
{
try
{
document.NewPage();
using (StringReader srHtml = new StringReader(pdfContentPage ))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, srHtml);
}
++cpt;
}
catch (RuntimeWorkerException ex)
{
Console.Write($"An error occured at PDF generation for cpt = {cpt}");
Console.Write(ex.Message);
}
catch (Exception)
{
Console.WriteLine($"Content Error : pdfContentPage}");
throw;
}
}
document.Close();
}
catch (Exception)
{
throw;
}
}
If you have an advice, I'm glad to read it ! :)
At the query binding field where & symbol comes i used a replace function for all describtion's For example at the bind grid s(2)=" TEST & TEST"
for loop
dim desc as string
desc="TEST & TEST"
desc=desc.replace("&"," ")
s(2)= desc
end of loop
Thus the issue was solved in my case
Try with below logic
InputStream is = new ByteArrayInputStream(srHtml.getBytes(Charset.forName("UTF-8")));
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, is, Charset.forName("UTF-8"));
With, xmlworker 5.5.12 and itextpdf 5.5.12 version

How to add header and footer txt file in C#?

I want to add a header and footer inside of my text file. How can i do that? My target should like This:
tr.AddHeaderAndFooter("Header","footer";
For example:
using (var fileStream = new FileStream(ConfigurationManager.AppSettings["TargetDir"] + swiftFile, FileMode.Open, FileAccess.Read))
{
TextReader tr = new StreamReader(fileStream);
tr.AddHeaderAndFooter("Header","footer";
}
A .txt file does not have a header or footer.
But you can simulate this behaviour with the following code sample:
// since there is no predefined method to add a string into the beginning
// of a file, you have to first read the whole file content into a temporary
// variable
string currentContent = String.Empty;
if (File.Exists(filePath))
{
currentContent = File.ReadAllText(filePath);
}
// now you can put your header into the beginning of the file so:
string header = "My Header";
File.WriteAllText(filePath, header + Environment.NewLine + currentContent );
// and finally you use the append method to add footer to the end of the file
string footer = "My Footer";
File.AppendAllText(filepath, Environment.NewLine + footer);
Do you mean something along the lines of:
string text = "header" + Environment.NewLine + "rest of file ... asjdhakjdh" + Environment.NewLine + "footer";
File.WriteAllText("filename.txt", text);
This will save
header
rest of file ... asjdhakjdh
footer
in a .txt file named filename.txt
So you could read your file, store it in a string, add your header and footer line and write it back to the same file it came from.

how to convert window form data into PDF

I am working on an Salary Project and what i want to do is
when an user see their Salary slip and click on Downloads then the complete form data is converted into PDf file and stored on an predifined location..
plz suggest the code to meet my requirements..
I had faced this problem before, and the best I found to solve it was to user Microsoft Word Interops. You can put whatever you want in a word document and then save it as PDF, fortunately Microsoft word allows you to export the document to PDF.
The simplest way to do this would be to save your data as just plain text, but don't forget to well format them, and then run this method to convert the plain text to PDF.
public PDFWriter(String Path, String FileName) {
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
try
{
word.Visible = false;
word.Documents.Open(Path);
word.ActiveDocument.SaveAs2(FileName + ".pdf", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
this.Path = FileName + ".pdf";
}
catch (Exception e)
{
word.Quit();
throw new Exception(e.Message);
}
finally
{
word.Quit();
}
}
Download pdfSharp.dll pdfSharp
and add it as reference.
Capture your form as image and then
private void ImageToPdf()
{
PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument();
PdfSharp.Pdf.PdfPage oPage = new PdfSharp.Pdf.PdfPage();
String destinaton = "your destination";
doc.Pages.Add(oPage);
XGraphics xgr;
XImage img;
img = XImage.FromGdiPlusImage(form image);
xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(oPage);
xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
}
valter

XMLWriter issues in C#

My issue is that I can't have the XML's file name be saved based on the text of a given field: here is the line:
XmlTextWriter writer = new XmlTextWriter(#"{0}\ops\op-" + OpName.Text.Replace(" ", "_") + ".xml",
System.Text.Encoding.UTF8);
The issue I get is that it can't find the path: C:\[stuff]\{0}\op\op-.xml and if I remove the {0}(in the code) I get can't find C:\op\op-.xml
I am needing it to find C:\[stuff]\op\ so it can make the file in that folder.
How could I change this line?
What does {0} represents in your path? XmlTextWriter constructor takes file path, not a formatted string. It would be much more readable if you'd prepare your file path in steps, eg. by utilizing Path.Combine method:
var fileName = string.Format("op-{0}.xml", OpName.Text.Replace(" ", "_"));
var rootDir = /* this would be {0} from your original example */
var filePath = Path.Combine(rootDir, "ops", fileName);
XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
string additionalStr=OpName.Text.Replace(" ", "_");
if (string.IsNullOrEmpty(additionalStr))
{
return;
//or throw error or make default file name depending on the required logic
}
string directoryPath=String.Format(#"{0}\ops\",dirPrefix);
bool isDirectoryExists=Directory.Exists(directoryPath);
if (!isDirectoryExists){
//required logic. for example set default directory
}
string fileName=additionalStr+".xml";
string filePath=Path.Combine(directoryPath,fileName);
XmlTextWriter writer = new XmlTextWriter(filePath,System.Text.Encoding.UTF8);

Categories