Pdf file is not updating in asp.net application - c#

In my asp.net application we generating pdf using ITextSharp.dll
Now my problem is every time same pdf is opening(not refreshing) unless until clear my browser history it is same. I am using chrome browser.
Here is my code
private void fillForm() {
try {
string Phone = "", Physical = "";
string formFile = Server.MapPath("~\\Inspection.pdf");
string newFile = Server.MapPath("~\\InspectionPrint.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = stamper.AcroFields;
PdfContentByte d = new PdfContentByte(stamper.Writer);
//getting values from DB
SqlCommand comd = new SqlCommand("usp_PrintInspection", QMSConn);
QMSConn.Open();
comd.CommandType = CommandType.StoredProcedure;
comd.Parameters.Add("#QuoteNumber", SqlDbType.VarChar);
comd.Parameters["#QuoteNumber"].Value = Session["CurrQuoteNumber"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlAdapter.SelectCommand = comd;
sqlAdapter.Fill(ds, "Table");
if (ds.Tables[0].Rows.Count > 0) {
// set form fields
string Name = ds.Tables[0].Rows[0]["NAME"].ToString();
string Address1 = ds.Tables[0].Rows[0]["Address1"].ToString();
string CompanyID = ds.Tables[0].Rows[0]["CompanyID"].ToString();
string PolicyNumber = ds.Tables[0].Rows[0]["PolicyNumber"].ToString();
fields.SetField("Name", Name);
fields.SetField("Address1", Address1);
fields.SetField("CompanyID ", CompanyID);
fields.SetField("PolicyNumber", PolicyNumber);
stamper.FormFlattening = false;
stamper.Close();
string file = "InspectionPrint";
string Url = "../" + file + ".pdf";
String js = #"WindowPopup('" + Url + "');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Key", js, true);
}
else {
showalert("No Record Available For This Quote");
}
}
catch(exception ex) {
}
}

as you are saying it is working in the Localhost but not in the production server, most likely it seems to me as an URL/Path issue.
1. after observing your code, you are creating one more string Url variable without using the existing String formFile variable.
as you should provide the valid path you need to use the formFile instead of Url as you have created formFile using Server.MapPath()
Try This:
/*string Url = "../" + file + ".pdf";*/ //comment or remove
String js = #"WindowPopup('" + formFile + "');";//use formFile instead of Url

Related

Generate PDF in using windows form

I want to generate a PDF using windows form in the desktop application. I have readymade pdf design and I just want to feed data from database in that blank section of pdf for each user. (One type of receipt). Please guide me. I have searched but most of the time there is the solution in asp.net for the web application. I want to do in the desktop app. Here is my code I am able to fatch data from database and print in pdf. But main problem is trhat I have already designed pdf and I want to place data exactly at same field (ie name, Amount, date etc.)
using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace printPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
int yPoint = 0;
string pubname = null;
string city = null;
string state = null;
connetionString = "Data Source=EEVO-SALMAN\\MY_PC;Initial Catalog=;User ID=s***;Password=******";
// var connectionString = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
sql = "select NAME,NAME,uid from tblumaster";
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
connection.Close();
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = "Database to PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Regular );
yPoint = yPoint + 100;
for (i = 0; i <=ds.Tables[0].Rows.Count-1; i++)
{
pubname = ds.Tables[0].Rows[i].ItemArray[0].ToString ();
city = ds.Tables[0].Rows[i].ItemArray[1].ToString();
state = ds.Tables[0].Rows[i].ItemArray[2].ToString();
graph.DrawString(pubname, font, XBrushes.Black, new XRect(10, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
graph.DrawString(city, font, XBrushes.Black, new XRect(200, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
graph.DrawString(state, font, XBrushes.Black, new XRect(400, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
yPoint = yPoint + 40;
}
string pdfFilename = "dbtopdf.pdf";
pdf.Save(pdfFilename);
Process.Start(pdfFilename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Instead of modifying the document, please create a new document and copy the pages from the old document to new document
sample code can be found here,
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637
Because modifying pdf is not recommended using 'PdfSharp' library. if you still want to edit you can use 'ISharp' library which needs a license.
Here is some VB.Net code I use to fill PDF forms. You need a PDF fillable form with form control names matching the SQL record field names.
It calls a routine Gen.GetDataTable() that just builds a typical DataTable. You could re-code to accept a pre-built Datatable as a parameter. Only the top row is processed. The code can be modified to work with a DataRow (.Table.Columns for column reference) or a DataReader.
Public Function FillPDFFormSQL(pdfMasterPath As String, pdfFinalPath As String, SQL As String, Optional FlattenForm As Boolean = True, Optional PrintPDF As Boolean = False, Optional PrinterName As String = "", Optional AllowMissingFields As Boolean = False) As Boolean
' case matters SQL <-> PDF Form Field Names
Dim pdfFormFields As AcroFields
Dim pdfReader As PdfReader
Dim pdfStamper As PdfStamper
Dim s As String = ""
Try
If pdfFinalPath = "" Then pdfFinalPath = pdfMasterPath.Replace(".pdf", "_Out.pdf")
Dim newFile As String = pdfFinalPath
pdfReader = New PdfReader(pdfMasterPath)
pdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
pdfReader.Close()
pdfFormFields = pdfStamper.AcroFields
Dim dt As DataTable = Gen.GetDataTable(SQL)
For i As Integer = 0 To dt.Columns.Count - 1
s = dt.Columns(i).ColumnName
If AllowMissingFields Then
If pdfFormFields.Fields.ContainsKey(s) Then
pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
Else
Debug.WriteLine($"Missing PDF Field: {s}")
End If
Else
pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
End If
Next
' flatten the form to remove editing options
' set it to false to leave the form open for subsequent manual edits
If My.Computer.Keyboard.CtrlKeyDown Then
pdfStamper.FormFlattening = False
Else
pdfStamper.FormFlattening = FlattenForm
End If
pdfStamper.Close()
If Not newFile.Contains("""") Then newFile = """" & newFile & """"
If Not PrintPDF Then
Process.Start(newFile)
Else
Dim sPDFProgramPath As String = INI.GetValue("OISForms", "PDFProgramPath", "C:\Program Files (x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe")
If Not IO.File.Exists(sPDFProgramPath) Then MsgBox("PDF EXE not found:" & vbNewLine & sPDFProgramPath) : Exit Function
If PrinterName.Length > 0 Then
Process.Start(sPDFProgramPath, "/t " & newFile & " " & PrinterName)
Else
Process.Start(sPDFProgramPath, "/p " & newFile)
End If
End If
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
Finally
pdfStamper = Nothing
pdfReader = Nothing
End Try
End Function

Getting multiple results from one select query

So I am stuck with my code and have thoroughly tried looking for an answer.
I have 1 select statement that brings about 52806 results.
I put the result of the query I run in variables and then put it into a PDF file i make. After the first result it doesn't work. I want to make it so that it puts the results in my pdf file and then goes to the next result.
if anyone can help me id appreciate it a lot.
Here is my code. Sorry for the bad practice in advance.
private void CreateBtn_Click(object sender, EventArgs e)
{
try
{
make_pdf();
}
catch (Exception exe )
{
MessageBox.Show("failed");
}
}
public static void make_pdf()
{
string Contact = "";
string emailAddress = "";
string Tel = "";
string InvoiceDate = "";
string address = "";
string Reference = "";
string AccountNo = "";
string Debit = "";
string Credit = "";
string refnum = "";
string connetionString = null;
MySqlConnection cnn;
connetionString = "server=********;user id=web_support;database=users;password=!w3b_supp0rt~;persistsecurityinfo=True";
cnn = new MySqlConnection(connetionString);
try
{
cnn.Open();
// MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
try
{
MySqlDataReader reader = null;
string selectCmd = "SELECT accounting.code,users.curr_email , users.physicaddr ,accounting.date , accounting.refnum , users.telephone , accounting.debit , accounting.acc_pdf, accounting.credit, accounting.reference, users.contact, accounting.transnum FROM accounting INNER JOIN users ON accounting.code = users.code WHERE(accounting.transtype = 1)";
MySqlCommand command = new MySqlCommand(selectCmd, cnn);
reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
//get account number
AccountNo = reader["code"].ToString();
//get emailaddress
emailAddress = reader["curr_email"].ToString();
//get Contact Name
Contact = reader["contact"].ToString();
//get telephone number
Tel = reader["telephone"].ToString();
//Get Date
InvoiceDate = reader["date"].ToString();
//Get reference
Reference = reader["reference"].ToString();
//Get Address
address = reader["physicaddr"].ToString();
//Get Debit
Debit = reader["debit"].ToString();
//Get Credit
Credit = reader["credit"].ToString();
//Get Refnum
refnum = reader["refnum"].ToString();
// MessageBox.Show(address+" "+Reference+" "+InvoiceDate+" "+emailAddress+" "+AccountNo+" "+Contact);
// Make The PDF File
Document NewDoc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
PdfWriter pdfwri = PdfWriter.GetInstance(NewDoc, new FileStream("text.pdf", FileMode.Create));
NewDoc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("intsa_header_small.jpg");
// Paragraph par = new Paragraph("Everything is working");
//Account List
List AccountNolist = new List(List.UNORDERED);
AccountNolist.SetListSymbol("");
AccountNolist.IndentationLeft = 300f;
AccountNolist.Add(new ListItem("AccountNo " + AccountNo));
// AddressList
List AddressList = new List(List.UNORDERED);
AddressList.SetListSymbol("");
AddressList.IndentationLeft = 300f;
AddressList.Add(new ListItem("Address: " + address));
#region Emailaddresslist
//EmailAddressList
List emailAddresslist = new List(List.UNORDERED);
emailAddresslist.SetListSymbol("");
emailAddresslist.IndentationLeft = 300f;
emailAddresslist.Add(new ListItem("Email address: " + emailAddress));
#endregion
//ContactList
List Contactlist = new List(List.UNORDERED);
Contactlist.SetListSymbol("");
Contactlist.IndentationLeft = 300f;
Contactlist.Add(new ListItem("Contact: " + Contact));
//TelephoneList
List Telephonelist = new List(List.UNORDERED);
Telephonelist.SetListSymbol("");
Telephonelist.IndentationLeft = 300f;
Telephonelist.Add(new ListItem("Tel: " + Tel));
// Make a Table
PdfPTable General_Table = new PdfPTable(1);
General_Table.SpacingBefore = 50f;
General_Table.SpacingAfter = 50f;
PdfPCell Caption = new PdfPCell(new Phrase("Description"));
PdfPCell Body = new PdfPCell(new Phrase(" " + refnum + " " + Reference + " Debit: " + Debit + " Credit: " + Credit));
Body.HorizontalAlignment = Element.ALIGN_RIGHT;
Caption.Colspan = 0;
Caption.HorizontalAlignment = 1;
General_Table.AddCell(Caption);
General_Table.AddCell(Body);
// NewDoc.Add(par);
//add Image to pdf
NewDoc.Add(img);
//add accountNo to pdf
NewDoc.Add(AccountNolist);
//add Contact to pdf
NewDoc.Add(Contactlist);
//add emailaddress to pdf
NewDoc.Add(emailAddresslist);
//add Telephone Number to pdf
NewDoc.Add(Telephonelist);
//add address to pdf
NewDoc.Add(AddressList);
NewDoc.Add(General_Table);
//save Pdf
NewDoc.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The problem is you are creating the PDF file in the while loop, I don't think you want 52k PDF files, so you should create the PDF file first, then loop through all of the results and paste them into the file.
EDIT: I would suggest adding line to insert/update PDF to database after
NewDoc.Close();
Then deleting the local file (text.pdf) before running loop again.

Can't upload file to Document Library using CSOM

I am trying to upload multiple file to a Document Library and also update its coloumn values.
List(Doc Lib) already exists but I am stuck with uploadinf the file
I've tried these methods
using lists.asmx
NetworkCredential credentials = new NetworkCredential("user", "Pass", "domain");
#region ListWebService
ListService.Lists listService = new ListService.Lists();
listService.Credentials = credentials;
List list = cc.Web.Lists.GetByTitle(library);
listService.Url = cc.Url + "/_vti_bin/lists.asmx";
try
{
FileStream fStream = System.IO.File.OpenRead(filePath);
string fName = fStream.Name.Substring(3);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
string attach = listService.AddAttachment(library, itemId.ToString(), Path.GetFileName(filePath), contents);
}
#endregion
catch (System.Web.Services.Protocols.SoapException ex)
{
CSVWriter("Message:\n" + ex.Message + "\nDetail:\n" +
ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace, LogReport);
}
It gives a error ServerException :To add an item to a document library, use SPFileCollection.Add() on AddAttachment()
Using
List lib = cc.Web.Lists.GetByTitle("TestLib");
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Content = System.IO.File.ReadAllBytes("C:\\Users\\AJohn\\Desktop\\sample.docx");
fileInfo.Url = "https://serverm/sites/Testing1/TestLib/sample.docx";
fileInfo.Overwrite = true;
Microsoft.SharePoint.Client.File upFile = lib.RootFolder.Files.Add(fileInfo);
cc.Load(upFile);
cc.ExecuteQuery();
I was able to upload once using this method, but now I am getting ServerException :To add an item to a document library, use SPFileCollection.Add() on cc.ExecuteQuery()
But if at all this method works, what I want is that I should update the coloumn values related to this file. In first method I get item.ID so from there I can update the Coloumn Values
Regarding the second method, the following example demonstrates how to upload a file into Documents library and set it's properties (e.g. Category text field)
using (var ctx = new ClientContext(webUri))
{
var targetList = ctx.Web.Lists.GetByTitle("Documents");
var fileInfo = new FileCreationInformation
{
Url = System.IO.Path.GetFileName(sourcePath),
Content = System.IO.File.ReadAllBytes(sourcePath),
Overwrite = true
};
var file = targetList.RootFolder.Files.Add(fileInfo);
var item = file.ListItemAllFields;
item["Category"] = "User Guide";
item.Update();
ctx.ExecuteQuery();
}

Why does this Sharepoint Files.Add() result in an I/O Error?

With this code:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 25, 25, 10, 10))
{
//Create a writer that's bound to our PDF abstraction and our
stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
. . .
}
// File has been generated, now save it
try
{
var bytes = ms.ToArray();
String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf",
pdfFileID);
String fileFullpath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirector
y), pdfFileName);
String fileLinkBase = "Generated PDF: {1}";
String filelink = String.Format(fileLinkBase, fileFullpath,
pdfFileName);
File.WriteAllBytes(fileFullpath, bytes);
AddVerticalSpace();
var pdflink = new Label
{
CssClass = "finaff-webform-field-label",
Text = filelink
};
this.Controls.Add(pdflink);
// NOTE: This is the new (non-working, exception-throwing) part of the
code, where we're trying to save the PDF file to a Sharepoint Document Library
string destination = String.Format("DirectPayPDFForms/{0}",
pdfFileName);
SPSite siteCollection = new SPSite(siteUrl);
SPWeb site = SPContext.Current.Web;
site.Files.Add(destination, ms); // this is the line that fails
// end of new code
}
catch (DocumentException dex)
{
exMsg = dex.Message;
}
catch (IOException ioex)
{
exMsg = ioex.Message;
}
catch (Exception ex)
{
exMsg = ex.Message;
; // for debugging: What is "ex" here?
}
} // using (var ms = new MemoryStream())
} // GeneratePDF
...I get, "I/O Error Occurred" (in the IOException catch block). It is this line:
site.Files.Add(destination, ms);
...that throws the error. Is it my destination, or the memory stream, that is causing the problem? "destination" is the name of the Sharepoint Document Library (DirectPayPDFForms) plus a generated name for the file. Without this new code, the method runs fine and places the PDF file on the server (but that's not where we want it - we need it to go first to a Document Library).
UPDATE
I get the same exception replacing the problematic code block above with a call to this:
private void SavePDFToDocumentLibrary(MemoryStream memstrm)
{
string doclib = "DirectPayPDFForms";
try
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists[doclib];
SPListItem spli = list.Items.Add();
spli["Title"] = String.Format("DirectPayPDFForms-{0}-{1}", GetUserId(), GetListTitleTimeStamp());
if (null != memstrm)
{
web.Files.Add(doclib, memstrm);
}
// If this works, update at least some of the fields, such as Created, CreatedBy, etc.
spli.Update();
}
}
}
catch (Exception ex)
{
String s = String.Format("Exception is {0}", ex.Message);
}
}
This type of code works in another instance (I can successfully save values to a List this way), so the problem must be something Document-Library-specific. Do I need to save the document to a specific field in the Document Library?
UPDATE 2
I also tried this:
string saveloc = String.Format(#"{0}\{1}", doclib, filename);
...with the same result.
And this:
string saveloc = String.Format(#"{0}\{1}\{2}", siteUrl, doclib, filename);
...which at least provided some variety, exceptioning with, "Invalid URI: The hostname could not be parsed."
With this:
string saveloc = String.Format("{0}/{1}/{2}", siteUrl, doclib, filename);
...I'm back to the old "I/O Error Occurred" mantra.
UPDATE 3
Since the "AllItems.aspx" page for the Sharepoint site has both "Documents" and "Lists", I am wondering if I should not be using List in this case, but Document. IOW, perhaps my code should be something like:
SPDocTemplateCollection spdoctemplatecoll = web.DocTemplates;
SPDocumentLibrary spdoclib = spdoctemplatecoll[doclib];
SPListItem spli = spdoclib.Items.Add();
...where it is currently:
SPList list = web.Lists[doclib];
SPListItem spli = list.Items.Add();
SPListItem spli = list.Items.Add();
...but that guess misses fire, as it won't compile (I get, "The best overloaded method match for 'Microsoft.SharePoint.SPDocTemplateCollection.this[int]' has some invalid arguments" and "Argument 1: cannot convert from 'string' to 'int'")
This works:
. . .
SavePDFToDocumentLibrary(fileFullpath); // instead of trying to send the memory stream, using the file saved on the server
. . .
private void SavePDFToDocumentLibrary(String fullpath)
{
String fileToUpload = fullpath;
String sharePointSite = siteUrl;
String documentLibraryName = "DirectPayPDFForms";
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
{
throw new FileNotFoundException("File not found.", fileToUpload);
}
SPFolder doclib = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = doclib.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
doclib.Update();
}
}
}
I adapted it from Henry Zucchini's answer here.

how to check file format

the allowed file format is only PDF file, how to check the file format and display error message if the uploaded file is not PDF before proceeding to update database. The following code always displays the file is not recognized even the file is PDF and also the database not updated.
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".pdf":
contenttype = "application/pdf";
break;
default:
System.Console.WriteLine("File format not recognised. Only PDF format allowed");
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string classNmae = ddClass.Text.Split('~')[0] + ddClass.Text.Split('1');
com.Parameters.Clear();
com.CommandText = "UPDATE [Marking] SET [fileName]=#fileName, [fileType]=#fileType, [type]=#typ,[submissionDate]=#sd, [filePath]=#fp where [class_id]=#cid AND [module_id]=#mid AND [student_id]= '" +Session["id"].ToString() + "'";
com.Parameters.Add("#cid", SqlDbType.VarChar).Value = ddClass.Text.Split('~')[0];
com.Parameters.Add("#mid", SqlDbType.VarChar).Value = ddClass.Text.Split('~')[1];
com.Parameters.Add("#fileName", SqlDbType.VarChar).Value = filename;
com.Parameters.Add("#fileType", SqlDbType.VarChar).Value = "application/pdf";
com.Parameters.Add("#typ", SqlDbType.VarChar).Value = txtType.Text;
com.Parameters.Add("#sd", SqlDbType.VarChar).Value = DateTime.Now;
com.Parameters.Add("#fp", SqlDbType.Binary).Value = bytes;
com.ExecuteNonQuery();
}
else
{
lb.Text = "File format not recognised." +
" Upload Word formats";
}
Try this:
if (FileUpload1.HasFile)
{
HttpPostedFile myPostedFile = FileUpload1.PostedFile;
FileInfo finfo = new FileInfo(myPostedFile.FileName);
if (finfo.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase) && IsPdf(finfo.FullName))
{
//do the operation
}
}
public bool IsPdf(string sourceFilePath)
{
var bytes = System.IO.File.ReadAllBytes(sourceFilePath);
var match = System.Text.Encoding.UTF8.GetBytes("%PDF-");
return match.SequenceEqual(bytes.Take(match.Length));
}
Updated as per #Darek's and #Andrew's suggestion.
Here is one way to find out if at least the file has a PDF header:
var bytes = File.ReadAllBytes(someFileNameHere);
var match = Encoding.UTF8.GetBytes("%PDF-");
var isPDF = match.SequenceEqual(bytes.Take(match.Length));

Categories