iTextSharp deleting document if there are no pages

Asked

Viewed 200 times

1

Well, I have an application that at a certain point generates a PDF with all JPG’s, however, instead of choosing a JPG I choose an Excel file it just moves this file.

Right, I’d like to get the document I created with iTextSharp (Doc.Open() among other properties) if you didn’t have any pages deleted, that weren’t created, any idea how to do this?

I already know that to know the number of pages is Doc.PageNumber

iTextSharp.text.Document Doc = new iTextSharp.text.Document(PageSize.A1, 20, 20, 20, 20);
            string PDFOutput = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
        PdfWriter writer = PdfWriter.GetInstance(Doc, new FileStream("C:/AgendaComp/Encaminhamento/" + txtNomePasta.Text + SID.ToString() + ".pdf", FileMode.Create, FileAccess.Write, FileShare.Read));

        Doc.Open();

        string Folder = @"C:/AgendaComp/Encaminhamento/" + txtNomePasta.Text + " arquivos/";
        foreach (string F in System.IO.Directory.GetFiles(Folder, "*.jpg"))
        {
            if (System.IO.File.Exists(F))
            {
                Doc.NewPage();

                //Doc.PageSize.Height = 1275;
                Doc.Add(new iTextSharp.text.Jpeg(new Uri(new FileInfo(F).FullName)));
            }
        }
        int n = Doc.PageNumber;
        if (n == 0)
        {
            Doc.Close();

        }
        else
        {
            Doc.Close();
            File.Move("C:/AgendaComp/Encaminhamento/" + txtNomePasta.Text + SID.ToString() + ".pdf", "C:/AgendaComp/Encaminhamento/" + DdataAviso.Year + "-" + DdataAviso.Month + "-" + DdataAviso.Day + "/" + txtNomePasta.Text + SID.ToString() + ".pdf");
        }
  • post the code you are using so far. It is probably possible to count the number of pages during document creation.

  • I have already counted the number of pages . I just can’t get the document to be deleted ,or not created . Like, if he doesn’t have a page, I don’t want it to exist

  • put the snippet of the code you are using to create the PDF

  • One option is to create the PDF in memory.

  • Ready, added the code, as I create it in memory ?

1 answer

1

To put into memory change the following lines:

PdfWriter writer = PdfWriter.GetInstance(Doc, new FileStream("C:/AgendaComp/Encaminhamento/" + txtNomePasta.Text + SID.ToString() + ".pdf", FileMode.Create, FileAccess.Write, FileShare.Read));

for

PdfWriter writer = PdfWriter.GetInstance(Doc, Response.OutputStream);

and after closing the document

 HttpResponse resp = this.Response;
 resp.ContentType = "application/pdf";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.