I have my temp PDF on the network and am using asp to fill in the fields and then download the file.
The problem I have is that the file downloaded is just the blank template, none of the fields are filled?
My code
Dim doc As New Document(PageSize.A4.Rotate)
Dim ms As New MemoryStream()
Dim writer = PdfWriter.GetInstance(doc, ms)
writer.Open()
Dim PdfR As New PdfReader("http://192.168.0.221/template.pdf")
Dim PdfS As New PdfStamper(PdfR, ms)
Dim fields As AcroFields = PdfS.AcroFields
fields.SetField("s1", "00")
fields.SetField("pono", "100")
PdfS.FormFlattening = True
PdfS.Close()
PdfR.Close()
Dim r = System.Web.HttpContext.Current.Response
r.ContentType = "application/pdf"
r.AddHeader("Content-Disposition", String.Format("attachment;filename=Testing.pdf", "Testing"))
r.BinaryWrite(ms.ToArray)
If anyone else ever hits this issue
1) If you dont mind your fields being editable then remove the FormFlattening command
2) Else add this fields.GenerateAppearances = True
Related
In the application I am working on I need to resize a picture and add it to the database I have implemented something to do so but I have a problem saving the resulting BMP file in the memory stream so that my implementation works with the existing code.Also the source from my image comes from a variable called fu (File upload object) I was also wondering if the way to access the source of the file is to use fu.name or fu.Filecontents. Also I have Enclosed what I implemented in beginning of my implementation and Ending of my implementation as the other code was done by a colleague who is not with me anymore.
Here is the code:
Public Function UploadFile(fu As FileUpload, expID As Integer) As Integer
GetConnectionString()
Dim con As New SqlConnection(connString.ConnectionString)
Dim dataAdapter As New SqlDataAdapter
Dim myCommandBuilder As SqlCommandBuilder
Dim dataSet As New DataSet
Dim memoryStream As MemoryStream
Dim bData As Byte()
Dim reader As BinaryReader
Dim expense As New Expense(expID)
Dim loggedInUser As New Employee(Membership.GetUser.UserName)
Try
UploadFile = 1
'check that the logged in user has the right to attach a file to the current expense
If loggedInUser.ID = expense.Rpt.Emp.ID Or loggedInUser.ID = expense.Rpt.Emp.Supervisor Or loggedInUser.ID = expense.Rpt.Emp.Finalizer Or loggedInUser.ID = expense.Rpt.Emp.DelegatedTo Then
If fu.HasFile Then
If fu.FileContent.Length < 5000000 Then
dataAdapter = New SqlDataAdapter("SELECT * FROM tblExpense WHERE EXPENSE_ID=" & expID, con)
myCommandBuilder = New SqlCommandBuilder(dataAdapter)
dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
con.Open()
dataAdapter.Fill(dataSet, "tblExpense")
'Begining of my implementation
' Get the scale factor.
Dim scale_factor As Single = Single.Parse(0.33)
' Get the source bitmap.
Dim bm_source As New Bitmap(fu.FileContent)
' Make a bitmap for the result.
Dim bm_dest As New Bitmap(
CInt(bm_source.Width * scale_factor),
CInt(bm_source.Height * scale_factor))
' Make a Graphics object for the result Bitmap.
Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)
' Copy the source image into the destination bitmap.
gr_dest.DrawImage(bm_source, 0, 0,
bm_dest.Width + 1,
bm_dest.Height + 1)
'Ending of my implementation
reader = New BinaryReader(fu.FileContent)
bData = reader.ReadBytes(reader.BaseStream.Length)
memoryStream = New MemoryStream(bData, 0, bData.Length)
memoryStream.Close()
dataSet.Tables("tblExpense").Rows(0)("RECEIPT") = bData
Select Case UCase(Right(fu.PostedFile.FileName, 3))
Case "JPG" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/jpeg"
Case "PNG" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/png"
Case "GIF" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/gif"
Case "PDF" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "application/pdf"
Case "TXT" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/plain"
Case "HTM" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/html"
Case "HTML" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/html"
Case Else : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/jpeg"
End Select
dataSet.Tables("tblExpense").Rows(0)("RECEIPT_NAME") = expense.Rpt.Emp.EmpNum & "-" & expense.Rpt.Name & "-" & expense.ID
dataSet.Tables("tblExpense").Rows(0)("RECEIPT_DATE") = Now
dataAdapter.Update(dataSet, "tblExpense")
Else
UploadFile = 2
Here is my issue: I'm trying to read JPG files from a folder and convert them to one PDF file for example if in my folder I have 1).Hello.jpg 2). World.jpg I want to grab those files and combined it to a one PDF file so the result will be
newPDF.pdf
I'm reading the images correctly from the folder adding them to the document but it's not creating the new PDF file in the folder. How can I solve this??
Here is my code:
'!=Orginally after setting all the files in the folder we need to read the path from the session file.
'!= After reading the path we need to read each file from the folder and generate one pdf file.
Dim attachmentsFolder As String = "E:/IRAttachments/PSC/2013/2/IR-7264"
Dim fileName As String = String.Concat("IR_7264(", DateTime.Now.ToString("yyyyMMddHHmmssfff").ToString(), ").pdf")
Dim finalPathName As String = String.Concat(attachmentsFolder, "/", fileName)
'!= Step 2). read the pdf/images from folder and merge them to a one pdf file.
Dim files As New List(Of String)()
Dim readerList As New List(Of PdfReader)()
m_HashTableIRAttachments = New Hashtable
m_DictionaryEntryIRAttachments = New DictionaryEntry
Dim fileExtentionType As String = String.Empty
Dim doc As Document = New Document
For Each filePath As String In Directory.GetFiles(attachmentsFolder)
fileExtentionType = filePath.Substring(filePath.LastIndexOf("."))
If fileExtentionType = ".jpg" Then '# Get the extension type
Dim document As New Document()
Using stream = New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)
PdfWriter.GetInstance(document, stream)
document.Open()
Using imageStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim image__1 = Image.GetInstance(imageStream)
document.Add(image__1)
Dim pdfFile As String = finalPathName
End Using
document.Close()
End Using
'PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + fileName, FileMode.Create))
'doc.Open()
'doc.Add(New Paragraph("Hello World"))
'Dim myDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
'Dim pdfFile As String = finalPathName
'Dim writer As PdfWriter = PdfWriter.GetInstance(myDoc, New FileStream(pdfFile, FileMode.Create))
'myDoc.Open()
'Dim para As New Paragraph("Let's write some text before inserting image.")
'Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(filePath)
'myImage.ScaleToFit(300.0F, 250.0F)
'myImage.SpacingBefore = 50.0F
'myImage.SpacingAfter = 10.0F
'myImage.Alignment = Element.ALIGN_CENTER
'myDoc.Add(para)
'myDoc.Add(myImage)
'myDoc.Close()
'doc.Close()
Else
'# Means it's a pdf and not a jpg file.
Dim pdfReader1 As New PdfReader(filePath)
readerList.Add(pdfReader1)
End If
Next
When you create the Stream for your PDF file, you are using the fileName variable, which is only the name, not the full path. It is likely that the PDF is being created - just not where you are expecting it to be. You probably want to use finalPathName instead:
Using stream = New FileStream(finalPathName, FileMode.Create, FileAccess.Write, FileShare.None)
I would also recommend you take a look at the methods available on the System.IO.Path class, and use them when constructing file paths and getting the file extension, e.g.
Dim finalPathName As String = Path.Combine(attachmentsFolder, fileName)
'...
fileExtentionType = Path.GetExtension(filePath)
' etc.
EDIT
It looks like you are also overwriting the PDF file for each image file, while I would imagine you want all of the images in one PDF file. Your loop for the images should probably be inside the Using stream = ... block (e.g. between document.Open() and document.Close()).
i'm trying to generate a report and export it to pdf in a loop, the report will receive a new parameter in each loop and prompt the client to download a PDF, in other words, the client may need to download 2 or 3 (or more) PDFs at the same time, the problem is that the prompt to accept the download only appears for the first pdf, dont know why. I can export to disk (server side) without any problems.
Code:
Sub PrintReport(ByVal Cod As Integer)
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.SQL
ConnInfo.ServerName = ConfigurationManager.AppSettings("SQLSERVERNAME")
ConnInfo.DatabaseName = ConfigurationManager.AppSettings("SQLDBNAME")
ConnInfo.UserID = ConfigurationManager.AppSettings("SQLSERVERUSER")
ConnInfo.Password = ConfigurationManager.AppSettings("SQLSERVERPASSWORD")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CrystalReportSource1.ReportDocument.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CrystalReportSource1.ReportDocument.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
Dim pField As ParameterField = CrystalReportSource1.ReportDocument.ParameterFields(0)
Dim val1 As ParameterDiscreteValue = New ParameterDiscreteValue
val1.Value = Cod
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
Dim PDFName As String = "PDF Nº " & Cod
CrystalReportSource1.ReportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, True, PDFName)
End Sub
EDIT:
Tried to zip the reports with DotNetZip but i get an broken zip.
Can you tell me whats wrong? (Solved: code bellow is corrected now)
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/zip"
Response.AppendHeader("content-disposition", "attachment; filename=AllPDFs.zip")
Using zipFile As New ZipFile()
For i = 0 To Cod.Length - 1
If Cod(i) > 0 Then
val1.Value = Cod(i)
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
val2.Value = Cod(i)
pField2.CurrentValues.Clear()
pField2.CurrentValues.Add(val2)
Dim PDFNameAs String = "PDF Nº " & Cod(i) & ".pdf"
Dim s As New System.IO.MemoryStream
s =CrystalReportSource1.ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat)
zipFile.AddEntry(PDFName, s)
End If
Next
zipFile.Save(Response.OutputStream)
End Using
Response.Clear()
Probably the response ends after the first one, therefore there's no response to write to for the 2nd and 3rd attempts.
Instead, you can have the client download the reports via AJAX Request (move your report generation into an .ashx generic handler), or have the user click the button 3 times to initiate new requests.
Or zip the PDF's up until a single file and allow the client to download that.
My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.
Hi can any one help me out for this.
I have RDLC Report displayed on my web page using asp.net And C#.net I want to export it to PDF on button click.
Please can you help me?
Thanks
I did something like this a while ago. Below is the code I used in the page_load event of a page. It is in VB and isn't the best code in the world but might help you get a solution..
Dim jobid As Integer = Request("jobid")
Dim rv As New Microsoft.Reporting.WebForms.ReportViewer
Dim r As String = "apps/Reports/legal_document.rdlc"
Dim ds As New jobmanagerTableAdapters.JobInformationTableAdapter
Dim ds2 As New ordermanagementTableAdapters.RecoveryItemsInformationTableAdapter
Dim ds3 As New expensemanagerTableAdapters.tbl_expensesTableAdapter
Dim ds4 As New ordermanagementTableAdapters.tbl_orders_collection_itemsTableAdapter
Dim ds5 As New attachmentsmanagerTableAdapters.tbl_attachmentsTableAdapter
Dim ds6 As New notesmanagerTableAdapters.tbl_notesTableAdapter
Dim ds7 As New payments_managerTableAdapters.tbl_paymentsTableAdapter
Dim rptSource1 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource2 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource3 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource4 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource5 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource6 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptsource7 As New Microsoft.Reporting.WebForms.ReportDataSource
rptSource1.Name = "jobmanager_JobInformation"
rptSource1.Value = ds.GetJobInfobyJobID(jobid)
rptSource2.Name = "ordermanagement_RecoveryItemsInformation"
rptSource2.Value = ds2.GetRecoveryItemsbyJobIDOrderID(jobid, 0)
rptSource3.Name = "expensemanager_tbl_expenses"
rptSource3.Value = ds3.GetExpensesbyJobIDOrderID(jobid, 0)
rptSource4.Name = "ordermanagement_tbl_orders_collection_items"
rptSource4.Value = ds4.GetDataByJobIDOrderID(jobid, 0)
rptSource5.Name = "attachmentsmanager_tbl_attachments"
rptSource5.Value = ds5.GetAllAttachmentsbyJobID(jobid)
rptSource6.Name = "notesmanager_tbl_notes"
rptSource6.Value = ds6.GetAllNotesbyJobID(jobid)
rptsource7.Name = "payments_manager_tbl_payments"
rptsource7.Value = ds7.GetPaymentsbyJobID(jobid)
rv.LocalReport.DataSources.Clear()
rv.LocalReport.ReportPath = r.ToString
rv.LocalReport.DataSources.Add(rptSource1)
rv.LocalReport.DataSources.Add(rptSource2)
rv.LocalReport.DataSources.Add(rptSource3)
rv.LocalReport.DataSources.Add(rptSource4)
rv.LocalReport.DataSources.Add(rptSource5)
rv.LocalReport.DataSources.Add(rptSource6)
rv.LocalReport.DataSources.Add(rptsource7)
'Page.Controls.Add(rv)
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
'Get folder on web server from web.config
Dim FolderLocation As String
FolderLocation = Server.MapPath("reports")
'First delete existing file
Dim filepath As String = FolderLocation & "\legal.PDF"
File.Delete(filepath)
'Then create new pdf file
bytes = rv.LocalReport.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Dim fs As New FileStream(FolderLocation & "\legal.PDF", FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
Response.Redirect("reports/legal.pdf")