Category Archives: PDF

[RESOLVED] pdf file search over string or text

Dear all,

I want to seach pdf files using asp.net C#.

if any pdf file content is "albert"  list that all files


or


search file on the basis of its content

thanks!

Hi umeshjha.net,

You can use the following code to open the pdf file, and find whether the pdf file contain the "albert" words.

using iTextSharp.text.pdf;
using iTextSharp.text;
  
private void openPDF()
{
            string str = "";
            string newFile = "c:\\New Document.pdf";
            Document doc = new Document();
  
            PdfReader reader = new PdfReader("c:\\New Document.pdf");
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                byte[] bt = reader.GetPageContent(i);
  
                str += ExtractTextFromPDFBytes(bt);
  
            }
}
  
  
 private string ExtractTextFromPDFBytes(byte[] input)
        {
            if (input == null || input.Length == 0) return "";
  
            try
            {
                string resultString = "";
  
                // Flag showing if we are we currently inside a text object
                bool inTextObject = false;
  
                // Flag showing if the next character is literal
                // e.g. '\\' to get a '\' character or '\(' to get '('
                bool nextLiteral = false;
  
                // () Bracket nesting level. Text appears inside ()
                int bracketDepth = 0;
  
                // Keep previous chars to get extract numbers etc.:
                char[] previousCharacters = new char[_numberOfCharsToKeep];
                for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' ';
  
  
                for (int i = 0; i < input.Length; i++)
                {
                    char c = (char)input[i];
  
                    if (inTextObject)
                    {
                        // Position the text
                        if (bracketDepth == 0)
                        {
                            if (CheckToken(new string[] { "TD", "Td" }, previousCharacters))
                            {
                                resultString += "\n\r";
                            }
                            else
                            {
                                if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters))
                                {
                                    resultString += "\n";
                                }
                                else
                                {
                                    if (CheckToken(new string[] { "Tj" }, previousCharacters))
                                    {
                                        resultString += " ";
                                    }
                                }
                            }
                        }
  
                        // End of a text object, also go to a new line.
                        if (bracketDepth == 0 &&
                            CheckToken(new string[] { "ET" }, previousCharacters))
                        {
  
                            inTextObject = false;
                            resultString += " ";
                        }
                        else
                        {
                            // Start outputting text
                            if ((c == '(') && (bracketDepth == 0) && (!nextLiteral))
                            {
                                bracketDepth = 1;
                            }
                            else
                            {
                                // Stop outputting text
                                if ((c == ')') && (bracketDepth == 1) && (!nextLiteral))
                                {
                                    bracketDepth = 0;
                                }
                                else
                                {
                                    // Just a normal text character:
                                    if (bracketDepth == 1)
                                    {
                                        // Only print out next character no matter what.
                                        // Do not interpret.
                                        if (c == '\\' && !nextLiteral)
                                        {
                                            nextLiteral = true;
                                        }
                                        else
                                        {
                                            if (((c >= ' ') && (c <= '~')) ||
                                                ((c >= 128) && (c < 255)))
                                            {
                                                resultString += c.ToString();
                                            }
  
                                            nextLiteral = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
  
                    // Store the recent characters for
                    // when we have to go back for a checking
                    for (int j = 0; j < _numberOfCharsToKeep - 1; j++)
                    {
                        previousCharacters[j] = previousCharacters[j + 1];
                    }
                    previousCharacters[_numberOfCharsToKeep - 1] = c;
  
                    // Start of a text object
                    if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters))
                    {
                        inTextObject = true;
                    }
                }
                return resultString;
            }
            catch
            {
                return "";
            }
        }
  
 private bool CheckToken(string[] tokens, char[] recent)
   {
     foreach (string token in tokens)
       {
          if ((recent[_numberOfCharsToKeep - 3] == token[0]) &&
           (recent[_numberOfCharsToKeep - 2] == token[1]) &&
           ((recent[_numberOfCharsToKeep - 1] == ' ') ||
           (recent[_numberOfCharsToKeep - 1] == 0x0d) ||
           (recent[_numberOfCharsToKeep - 1] == 0x0a)) &&
           ((recent[_numberOfCharsToKeep - 4] == ' ') ||
           (recent[_numberOfCharsToKeep - 4] == 0x0d) ||
           (recent[_numberOfCharsToKeep - 4] == 0x0a))
                 )
           {
                    return true;
            }
            }
            return false;
        }


Please check the following link:

http://www.codeproject.com/KB/showcase/TallComponents.aspx

[RESOLVED] how to display an PdF dynamiclly in iframe

Hello all,

i have an ifram in a web page and i want dynamiclly to pop a pdf.

i am generating a pdf into a byte[] .

is it possible to bind the ifram with the byte[]?

Please help me ..

NirNiroN

Create a new page and do a response.BinaryWrite your byte array in Page Load

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(bytes.ToArray());
    }
    catch (Exception ex) 
    {
        throw ex; 
    }
}

And set Iframe Src to the new page. That's it

[RESOLVED] how to pop PDF dynamiclly within a iframe

hello i have an aspx  which contains an iframe in it.

i want to pop an PDF  into an iframe dynamiclly.

i have the PDF in a byte[] and my questionis how shall i display it in the iframe?

please i need help..

NirNiroN

1) create .ashx handler which will show pdf
2) point iframe to .ashx link 

Use Jquery Fancy box to show popups

[RESOLVED] how to open a pdf file in a new window

Hi, I have a button that once clicked it open a pdf file in the same window. I need to be able to open in a new window

How can I open this pdf in a new window.

        protected void btnPrint_Click(object sender, EventArgs e)
        {    // generate pdf file
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("ID", txtID.Text);
            aslBL.Reporting rpt = new Reporting(xxx, xxx, xxx);
            byte[] ret = rpt.Render(System.Configuration.ConfigurationSettings.AppSettings["reportName"], Reporting.Format.PDF, d);
            if (!ret.Length.Equals(0))
            {
                Response.Expires = 0;
                Response.Buffer = true;
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "inline; filename=myReport.pdf");
                Response.AddHeader("Content-Length", ret.Length.ToString());
                Response.BinaryWrite(ret);
            }
        }

 

The reason for my request is that before a user click on print report, a user click on a button to make some of the controls on the page grayed out - enabled = false; so when a user click on print report, a pdf document open BUT once he click on return back in the browser, all the controls that were grayed out are back. so how to fix this issue. i thought to open a new window for the pdf.

If you have a better solution, please share it with me.

Thanks

 

Bob

Your description is not fully clear to me about pressing a control to disable some cotnrol and then press a button to open PDF!

But based on my understaing you can try these options:

1. Create a seperate aspx page something like showpdf.aspx, which contains the same code as on button click but on page_load, you can pass parameter to this page in querystring or session, whatever suits your situation. OnClientClick of Button you can call window.open function in javascript, that will launch showpdf.aspx and display pdf.

2. another options is, if you need to do some data processing etc. then you can use button click and then then use Page.RegisterClientScript or Page.RegisterStartipScript function to launch showpdf.aspx.

I hope this helps. you can find lots of example on javascript:window.open('pagename','options'); or how to use Page.RegisterStartupScript() function.

In the html part of that button "btnPrint" please add this.

OnClientClick="aspnetForm.target ='_blank';"

Hi and thanks for your prompt response. I tried this code and did not work. I am not sure if I understood what you ment by aspnetForm .I  assumed it i sthe aspx page to be opened... please advise.........thanks bob

 

 

<asp:Button ID="btnOpenNewWindow" runat="server" Text="Open new window"

 

OnClientClick

="Target.aspx.target ='_blank';"/>

<div style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; width: 100%; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #ffffff; margin: 8px;">

HI,

open new window on ur btnprint

OnClientClick="window.open('showPdf.aspx','','menubar=no,resizable=yes,scrollbars=yes');"

and in showpdf.aspx page load write ur code (which is written on print button)

u can pass paramater in showpdf page in case it required...

</div>

Thanks for your reply,

Is there a way that I can control all different attributes of the open window. for instance. I want to have a full control of the new open window so I can show/ hide the back button, and other items in the opened window.... thanks (:

Bob

thanks it worked

[RESOLVED] Detect text file during uplaod

Hi,

on my website I have file uploading (only text files). How to detect correct file type? 

Reading first 8 bytes doesn't works here because there are text files.

Any ideas?

Did you try checking the extension?

string extenstion = Path.GetExtension(filename);
        if (extenstion != ".txt")
        {
        }

This approach is not safe.

Hi,

olo21

How to detect correct file type? 

There's several methods you can do to control the type of upload file.

One is to use validation controls, it can force the checking to be done on the client. Of course, it need the browser allow client side use of the validation controls.

Check:http://www.developer2blog.com/post/2011/02/07/File-Upload-Control-File-Type-Validation.aspx

Second is use server side code to check file type. This method allow the file upload to server, but before save the file, it will first check the type on server.

You can check:http://www.beansoftware.com/ASP.NET-FAQ/FileUpload-Validation.aspx

If you want to a more secure way. I suggest to use both client side and server side validation

Hope this can help you.

hi..

when uploading ,you wanto check the file extension means you have to use httpfileuploaded,try this link to know more aboout this function 

http://vbdotnetaddict.blogspot.com/2011/02/upload-image-or-file-into-database-in.html

Use RegularExpressionValidator and also in case use customValidator with serverside function to actually validate the text file...

Thanks.

All your solutions are good but there is one disadvantage: they work based on a file extension. Is any other way to detect text files?

Hi,

olo21

they work based on a file extension

If you do not want to check the extension. The way I can think out is to use the server code: FileUpload1.PostedFile.ContentType.

After text files post to server. Use above code to check the mine type(text/plain). But also notice that, if user changed the file extension manually. The mine type will not be correct as we expect. Seems that if I changed the txt to jpg or pdf, the mine type is correct. But like .doc or other extension. The type will changed also.

Hope this can help you.

Hi,

olo21

they work based on a file extension

If you do not want to check the extension. The way I can think out is to use the server code: FileUpload1.PostedFile.ContentType.

After text files post to server. Use above code to check the mine type(text/plain). But also notice that, if user changed the file extension manually. The mine type will not be correct as we expect. Seems that if I changed the txt to jpg or pdf, the mine type is correct. But like .doc or other extension. The type will changed also.

Hope this can help you.