Adding text a pdf while downloading (streaming) from ftp with itextsharp - c#

I have some code for showing pdf files in browser that come from ftp. I have to add some text to pdf that come from ftp. And I found some working codes for it from antoher projects but it writes to pdf from iis local path.
//** these are my working code that show pdf files in browser from ftp. **//
string filename = Request.QueryString["view"];
string ftpServerIP = Session["Host"].ToString();
string ftpUserName = Session["user"].ToString();
string ftpPassword = Session["pssw"].ToString();
FileInfo objFile = new FileInfo(filename);
System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));
request.Credentials = new NetworkCredential(SftpUserName, ftpPassword);
request.Method = WebRequestMethods.Ftp.GetFileSize;
System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();
int length = (int)(response.ContentLength * 1.1);
request = (System.Net.FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
request.Method = WebRequestMethods.Ftp.DownloadFile;
response = (System.Net.FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
BinaryReader br = new BinaryReader(responseStream);
byte[] buffer = br.ReadBytes(length);
//** Can I work the itextsharp codes near here for adding text, without saving local, before download? **//
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentEncoding = reader.CurrentEncoding;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["name"]);
Response.BinaryWrite(buffer);
//** these are another code which I need to implement my code for adding some text in pdf files.**//
//** these are not my actual codes, just from another project's and I have to use them in my project.**//
//** The difference is in my project download pdf directly from an ftp, other one reads pdf in local files.**//
private void WriteToPdf(FileInfo sourceFile, string outbut_File, string stringToWriteToPdf)
{
PdfReader reader = new PdfReader(sourceFile.FullName);
PdfStamper pdfStamper = new PdfStamper(reader, new System.IO.FileStream(outbut_File, FileMode.Create, FileAccess.Write, FileShare.Write));
iTextSharp.text.pdf.PdfGState Gstates = new iTextSharp.text.pdf.PdfGState();
Gstates.StrokeOpacity = 0.3f;
Gstates.FillOpacity = 0.3f;
for (int i = 1; i <= reader.NumberOfPages; i++)
{
iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(i);
PdfContentByte pdfPageContents = pdfStamper.GetOverContent(i);
pdfPageContents.BeginText();
BaseFont baseFont__1 = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
//BaseFont.CreateFont("", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED)
pdfPageContents.SetFontAndSize(baseFont__1, 15);
pdfPageContents.SetRGBColorFill(255, 0, 0);
pdfPageContents.SaveState();
float textAngle = 0;
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, stringToWriteToPdf, 5, 5, textAngle);
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, stringToWriteToPdf, pageSize.Width, pageSize.Height, textAngle);
pdfPageContents.EndText();
}
pdfStamper.FormFlattening = true;
pdfStamper.Close();
reader.Close();
Stream s = File.OpenRead(outbut_File);
byte[] buffer = new byte[s.Length + 1];
try
{
s.Read(buffer, 0, (Int32)s.Length);
}
finally
{
s.Close();
}
Response.ClearContent();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["name"]);
Response.WriteFile(outbut_File);
Response.End();
}
How should I customise these codes from downloading ftp and adding text then showing in browser?

Related

PDFsharp not giving pdf file in response

I am working on export functionality using PDFsharp in .Net MVC I am not getting any error in my code but not getting PDF file in response.
I have tried doing it manually writing it to specific path with the help of : System.IO.File.WriteAllBytes(path1, bytes); and it's working perfectly, but I am not getting PDF in Response with the help of
Response.BinaryWrite(bytes);
Response.OutputStream.Write(bytes, 0, bytes.Length);
Anyone have faced this type of issue or someone from community please help
Here is my code :
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Myfile.pdf");
Response.ContentType = "application/pdf";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document =
PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4,
30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
var path1 = Server.MapPath("~/Images/" +
DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.BinaryWrite(bytes);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.End();
return true;
}
thank you,

Value cannot be null. Parameter name: elementId in PDFsharp

I am working on Export to PDF funtionality using C# and PDFSharp. I am getting this error:
Value cannot be null.
Parameter name: elementId
The error is on this line :
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
Here's the whole method:
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=Myfile.pdf");
//Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
//Response.AppendHeader("Content-Disposition", "attachment; filename=Myfile.pdf");
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
//PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl, config);
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
//var path1 = Server.MapPath("~/Images/" + DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.TransmitFile(path1, 0, bytes.Length);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return true;
}
That exception can occur if you have a blank anchor tag.
It is likely ultimately being generated from here.
You should remove the blank anchor tag.

Issues with downloading PDF file from source

iv'e created a method to generate a pdf file from a form, it got saved to the correct path using itexsharp, but the problem is i can't download it.
this is my code :
private void FillForm(Dictionary<string, string> dic)
{
var pdfTemplate = HttpContext.Current.Server.MapPath("~/ress/GENE_15_04_2014.pdf"); //_pdfTemplet;
var newFile = _newFileName + "_" + Guid.NewGuid() + ".pdf";
_gNewFile = newFile.ToString();
var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate));
var pfileStream = new FileStream(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", newFile), FileMode.Create);
var pdfStamper = new PdfStamper(pdfReader, pfileStream);
var pdfFormFields = pdfStamper.AcroFields;
foreach (var entry in dic)
{
pdfFormFields.SetField(entry.Key, entry.Value);
}
pdfStamper.FormFlattening = true;
pdfStamper.JavaScript = "this.print(true);\r";
pdfStamper.Writer.CloseStream = false;
pdfReader.Close();
pdfStamper.Close();
UPContract.Update();
pfileStream.Close();
pdf.FilePath = string.Format("../Ress/{0}", Path.GetFileName(_gNewFile));
Response.Clear();
byte[] bytes = System.IO.File.ReadAllBytes(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", _gNewFile));
Response.ContentType = "application/pdf";
MemoryStream ms = new MemoryStream(bytes);
Response.AddHeader("content-disposition", "attachment;filename=" + "fiche abonnement_" + _gNewFile + ".pdf");
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
If you want to pass a file you can skip the byte array and MemoryStream and just use Response.WriteFile(string)

ASP.NET convert and download pdf using ClosedXML and Spire.XLS

I use Web Forms. I try to convert ClosedXML excel workbook to pdf using Spire.XLS and download it by a client.
Here is my code:
protected void btnExport_OnClick(object sender, EventArgs e)
{
var excel = Reporting.GenerateExcel(); //custom, return XLWorkbook object
string myName = Server.UrlEncode(121 + "_" + DateTime.Now.ToShortDateString() + ".xlsx");
MemoryStream stream = GetStream(excel);
MemoryStream stream1 = new MemoryStream();
Workbook book = new Workbook();
book.LoadFromStream(stream);
book.SaveToStream(stream1, FileFormat.PDF);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + myName);
Response.ContentType = "application/pdf";
Response.BinaryWrite(stream1.ToArray());
Response.End();
}
public MemoryStream GetStream(XLWorkbook excelWorkbook)
{
MemoryStream fs = new MemoryStream();
excelWorkbook.SaveAs(fs);
fs.Position = 0;
return fs;
}
It seems like I receive not correct pdf. Thanks

How to write FDF to PDF using iTextSharp c#

I have this example to fill a FDF programmatically and to visualize it.
private readonly string pdfFormFileName = "PDFForm.pdf";
protected void OpenPDF_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/vnd.fdf";
FdfWriter fdfWriter = new FdfWriter();
fdfWriter.File = GetAbsolutePath() + pdfFormFileName;
fdfWriter.SetFieldAsName("txtFirstName", FirstName.Text);
fdfWriter.SetFieldAsName("txtLastName", LastName.Text);
Response.AddHeader("Content-disposition", "inline; filename=FlatPDFForm.fdf");
fdfWriter.WriteTo(Response.OutputStream);
Response.End();
}
Instead of displaying the file, I need to save it to a file.
Could you pls help me?
I found the solution!
string newFile = Server.MapPath("~/") + "ModF23_Final.pdf";
string pdfTemplate = Server.MapPath("~/") + "ModF23.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("2", FirstName.Text);
pdfFormFields.SetField("2-1", LastName.Text);
pdfStamper.FormFlattening = true;
pdfStamper.Close();
Andrea could you try using this line of code
Response.ClearHeaders();
Response.ContentType = "application/vnd.fdf";
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;Filename=FlatPDFForm.fdf");
Response.TransmitFile("FlatPDFForm.fdf");
Response.End();
Comment out this line fdfWriter.WriteTo(Response.OutputStream);
ADDED correct ContentType

Categories