I'm creating a pdf file this is my code:
public ActionResult ImprimirPedido()
{
List<ReporteModel> lista = new List<ReporteModel>();
ReporteModel obj = new ReporteModel();
obj.Responsable = "juan peres";
obj.TipoPago = "Efectivo";
obj.Fecha = "02/05/2014";
obj.NombreProducto = "chocolate";
obj.Cantidad = "2";
obj.Total = "54.00";
lista.Add(obj);
string directorio = "~/Models/";
string urlarchivo = string.Format("{0}.{1}", "Reporte_Disenio", "rdlc");
string fullpath = string.Format("{0}{1}", this.HttpContext.Server.MapPath(directorio), urlarchivo);
ReportViewer repor = new ReportViewer();
repor.Reset();
repor.LocalReport.ReportPath = fullpath;
ReportDataSource data = new ReportDataSource("DS_REPORT", lista);
repor.LocalReport.DataSources.Add(data);
repor.LocalReport.Refresh();
byte[] file = repor.LocalReport.Render("PDF");
return File(new MemoryStream(file).ToArray(),
System.Net.Mime.MediaTypeNames.Application.Octet,
string.Format("{0}{1}", "archivo.", "PDF"));
}
Now I want to print directly on the printer without preview, the printer is installed on my pc with iis. here run my systema mvc4 .net.
Related
I want to load in a JPEG file and print it with Aspose.Pdf in C# (.net Framework 4.8). The code I currently have is:
public void PrintImage(string fileToPrint, string printerName, string jobName)
{
System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileToPrint);
int h = srcImage.Height;
int w = srcImage.Width;
var doc = new Document();
var page = doc.Pages.Add();
var image = new Image();
image.File = (fileToPrint);
page.PageInfo.Height = (h);
page.PageInfo.Width = (w);
page.PageInfo.Margin.Bottom = (0);
page.PageInfo.Margin.Top = (0);
page.PageInfo.Margin.Right = (0);
page.PageInfo.Margin.Left = (0);
page.Paragraphs.Add(image);
var viewer = new PdfViewer(doc);
PrintUsingViewer(viewer, printerName, jobName);
}
private static void PrintUsingViewer(PdfViewer viewer, string printerName, string jobName)
{
viewer.AutoResize = true; // Print the file with adjusted size
viewer.AutoRotate = true; // Print the file with adjusted rotation
viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
var ps = new System.Drawing.Printing.PrinterSettings();
var pgs = new System.Drawing.Printing.PageSettings();
ps.PrinterName = printerName;
viewer.PrinterJobName = jobName;
viewer.PrintDocumentWithSettings(pgs, ps);
viewer.Close();
}
When I save the document instead of printing and look at it, it seems fine (the image is added). However, when trying to print the image it is not printed and the page is just blank..
I would like to print without first saving the document as a PDF and then trying to print that saved PDF. Does anyone see what I am doing wrong?
The solution was adding this line of code
doc.ProcessParagraphs();
right after this line:
page.Paragraphs.Add(image);
So the code now becomes
public void PrintImage(string fileToPrint, string printerName, string jobName)
{
System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileToPrint);
int h = srcImage.Height;
int w = srcImage.Width;
var doc = new Document();
var page = doc.Pages.Add();
var image = new Image();
image.File = (fileToPrint);
page.PageInfo.Height = (h);
page.PageInfo.Width = (w);
page.PageInfo.Margin.Bottom = (0);
page.PageInfo.Margin.Top = (0);
page.PageInfo.Margin.Right = (0);
page.PageInfo.Margin.Left = (0);
page.Paragraphs.Add(image);
doc.ProcessParagraphs();
var viewer = new PdfViewer(doc);
PrintUsingViewer(viewer, printerName, jobName);
}
private static void PrintUsingViewer(PdfViewer viewer, string printerName, string jobName)
{
viewer.AutoResize = true; // Print the file with adjusted size
viewer.AutoRotate = true; // Print the file with adjusted rotation
viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
var ps = new System.Drawing.Printing.PrinterSettings();
var pgs = new System.Drawing.Printing.PageSettings();
ps.PrinterName = printerName;
viewer.PrinterJobName = jobName;
viewer.PrintDocumentWithSettings(pgs, ps);
viewer.Close();
}
Now the image is printed correctly!
This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default
I have the following code:
private void CreateExcel(string fileName)
{
var operationDate = System.DateTime.ParseExact(txtStartDate.Text, "dd/MMM/yyyy", CultureInfo.CurrentCulture);
var ds1 = new _spAvailabilityEventDailyReport1TableAdapter();
var ds2 = new _spAvailabilityEventDailyReport2TableAdapter();
var ds3 = new _spAvailabilityEventDailyReport3TableAdapter();
var ds4 = new _spAvailabilityEventTotalTableAdapter();
var ds5 = new _spAvailabilityNoteDailyReportTableAdapter();
var ds6 = new _spAvailabilityDailyReportTableAdapter();
var ds7 = new _spAvailabilityReadingTotalTableAdapter();
var ds8 = new _spAvailabilityEventSum1TableAdapter();
var ds9 = new _spAvailabilityEventSum2TableAdapter();
var ds10 = new _spAvailabilityEventSum3TableAdapter();
//default margin setting
string outputType = "Excel";
string pageHeight = "11.69in";
string pageWidth = "8.27in";
string marginTop = "0.3937in";
string marginBottom = "0.3937in";
string marginLeft = "0.3937in";
string marginRight = "0.3937in";
string reportPath = Server.MapPath("~/rdlc/dailyavailability.rdlc");
try
{
//search setting margin report & kind output export -> for parameter 2nd render RDLC
var xml = System.IO.File.ReadAllText(reportPath);
var matches = Regex.Matches(xml, #"<(?<property>PageHeight|PageWidth|TopMargin|BottomMargin|LeftMargin|RightMargin)>(?<value>[^<]+)</\k<property>>", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (!match.Success)
continue;
switch (match.Groups["property"].Value)
{
case "PageHeight":
pageHeight = match.Groups["value"].Value;
break;
case "PageWidth":
pageWidth = match.Groups["value"].Value;
break;
case "TopMargin":
marginTop = match.Groups["value"].Value;
break;
case "BottomMargin":
marginBottom = match.Groups["value"].Value;
break;
case "LeftMargin":
marginLeft = match.Groups["value"].Value;
break;
case "RightMargin":
marginRight = match.Groups["value"].Value;
break;
}
}
}
catch (System.Exception) { }
string reportType = string.IsNullOrEmpty(outputType) ? "Excel" : outputType.Trim().ToUpper();
string encoding;
string deviceInfo = string.Format(#"<DeviceInfo>
<OutputFormat>{6}</OutputFormat>
<PageWidth>{0}</PageWidth>
<PageHeight>{1}</PageHeight>
<MarginTop>{2}</MarginTop>
<MarginLeft>{3}</MarginLeft>
<MarginBottom>{4}</MarginBottom>
<MarginRight>{5}</MarginRight>
</DeviceInfo>", pageWidth, pageHeight, marginTop, marginLeft, marginBottom, marginRight, reportType);
var rds = new ReportDataSource("dsAvailabilityEventDailyReport1", (DataTable)ds1.GetData(operationDate)); //fill data report in parameter
var rds2 = new ReportDataSource("dsAvailabilityEventDailyReport2", (DataTable)ds2.GetData(operationDate)); //fill data report in parameter
var rds3 = new ReportDataSource("dsAvailabilityEventDailyReport3", (DataTable)ds3.GetData(operationDate)); //fill data report in parameter
var rds4 = new ReportDataSource("dsAvailabilityEventTotal", (DataTable)ds4.GetData(operationDate)); //fill data report in parameter
var rds5 = new ReportDataSource("dsAvailabilityNoteDailyReport", (DataTable)ds5.GetData(operationDate)); ///fill data report in parameter
var rds6 = new ReportDataSource("dsAvailabilityDailyReport", (DataTable)ds6.GetData(operationDate)); //fill data report in parameter
var rds7 = new ReportDataSource("dsAvailabilityReadingTotal", (DataTable)ds7.GetData(operationDate)); //fill data report in parameter
var rds8 = new ReportDataSource("dsAvailabilityEventSum1", (DataTable)ds8.GetData(operationDate)); //fill data report in parameter
var rds9 = new ReportDataSource("dsAvailabilityEventSum2", (DataTable)ds9.GetData(operationDate)); //fill data report in parameter
var rds10 = new ReportDataSource("dsAvailabilityEventSum3", (DataTable)ds10.GetData(operationDate)); //fill data report in parameter
// Variables
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string extension = string.Empty;
// Setup the report viewer object and get the array of bytes
var report = new LocalReport();
report.ReportPath = reportPath;
report.DataSources.Add(rds); // Add datasource here
report.DataSources.Add(rds2); // Add datasource here
report.DataSources.Add(rds3); // Add datasource here
report.DataSources.Add(rds4); // Add datasource here
report.DataSources.Add(rds5); // Add datasource here
report.DataSources.Add(rds6); // Add datasource here
report.DataSources.Add(rds7); // Add datasource here
report.DataSources.Add(rds8); // Add datasource here
report.DataSources.Add(rds9); // Add datasource here
report.DataSources.Add(rds10); // Add datasource here
//set parameter report (jika ada)
report.SetParameters(new List<ReportParameter>
{
//new ReportParameter("FacilitySubClassID", facilitySubClassId.ToString()),
new ReportParameter("OperationDate", operationDate.ToString())
});
byte[] bytes = report.Render(reportType, deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "." + extension + "\"");
Response.BinaryWrite(bytes); // create the file
Response.Flush(); // send it to the client to download
}
I have a sub-report on my rdlc report,, when i tried to export it to excel. The error message appear on excel file (sub-report section).
"Data retrieval failed for the subreport, 'srAvailabilityList', located at: C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\coco\rdlc\availabilityreading.rdlc. Please check the log files for more information."
The sub-report is using ds6 and ds7.
My questions are:
How can I retrieve the data in the sub-report?
Where I can find the log files?
Found the answer:
void MySubreportEventHandler(object sender, SubreportProcessingEventArgs e)
{
var operationDate = System.DateTime.ParseExact(txtStartDate.Text, "dd/MMM/yyyy", CultureInfo.CurrentCulture);
var ds6 = new _spAvailabilityDailyReportTableAdapter();
var ds7 = new _spAvailabilityReadingTotalTableAdapter();
var rds6 = new ReportDataSource("dsAvailabilityDailyReport", (DataTable)ds6.GetData(operationDate)); //isi data report di parameter kedua
var rds7 = new ReportDataSource("dsAvailabilityReadingTotal", (DataTable)ds7.GetData(operationDate)); //isi data report di parameter kedua
e.DataSources.Add(rds6);
e.DataSources.Add(rds7);
}
Then add this code before report.SetParameter :
report.SubreportProcessing += new SubreportProcessingEventHandler(MySubreportEventHandler);
I have a pdf template I created using LiveCycle Designer. Inside it, I have 3 Image Fields that I created, ImageField1, ImageField2, ImageField3. The images are located on a url, let's call it "http://images.com/img/IMAGENAME.jpg", and the user selects the images prior to generating the pdf in which case I store the image names in a string array.
Is it possible to add these images programmatically into the Image Fields? The methods I've tried so far have only lead to a corrupted pdf that won't open at all.
public string Foo(int id)
{
try
{
var file = string.Empty;
var property = ((IRepositoryBase)PropertyRepository).GetById<Property>(id);
var purchase = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyPurchase>(id);
var inspection = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyInspection>(id);
file = HttpContext.Current.Server.MapPath("\\Assets\\documents\\originals\\Brochure.pdf");
var tmp = HttpContext.Current.Server.MapPath("\\Assets\\documents\\temps\\");
tmp += string.Format("{0}-Brochure.pdf", property.Id);
var pdfReader = new PdfReader(file);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(tmp, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
var pht = property.BrochurePhoto;
string[] photos = pht.Split(' ');
PdfContentByte cB = new PdfContentByte(pdfStamper.Writer);
if (photos[0] != null)
{
iTextSharp.text.Image photoToPdf1 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[0].ToString() + ".jpg"));
cB.AddImage(photoToPdf1);
}
if (photos[1] != null)
{
iTextSharp.text.Image photoToPdf2 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[1].ToString() + ".jpg"));
cB.AddImage(photoToPdf2);
}
if (photos[2] != null)
{
iTextSharp.text.Image photoToPdf3 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[2].ToString() + ".jpg"));
cB.AddImage(photoToPdf3);
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
return string.Format("{0}-Brochure.pdf", property.Id);
}
catch (Exception ex)
{
Log.Error(ex);
return string.Empty;
}
}
I had an grid view where I had placed an link button to print an report. In this button click event I need to call the SSRS report and need to get the output as PDF file.
I had used this below code,the code is running fine, but I'm unable to see the prompt to open/save pdf file.
protected void btnAuthenticateAndPrint_Click(object sender, EventArgs args)
{
try
{
//Getting Values from grid
LinkButton lb = (LinkButton)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
Label lbOrderID = row.FindControl("lbOrderID") as Label;
int OrderId = Convert.ToInt32(lbOrderID.Text);
da = new SqlDataAdapter("Get_PODetails", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#MPDI_ID", OrderId);
ds = new DataSet();
da.Fill(ds, "PO");
if (ds.Tables["PO"].Rows.Count > 0)
{
lblPOId.Text=ds.Tables["PO"].Rows[0]["MPDI_ID"].ToString();
lblVendid.Text = ds.Tables["PO"].Rows[0]["MVDI_ID"].ToString();
lblBranch.Text = ds.Tables["PO"].Rows[0]["MBRI_ID"].ToString();
lblDate.Text = Convert.ToDateTime(ds.Tables["PO"].Rows[0]["MPDI_Date"]).ToString("dd-MM-yyyy");
}
//SSRS Report Print
rs = new RSWebService.ReportingService2005();
rsExec = new REWebService.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://localhost/ReportServer/ReportService2005.asmx";
rsExec.Url = "http://localhost/ReportServer/ReportExecution2005.asmx";
byte[] Sendresults = null;
byte[] bytes = null;
string historyID = null;
string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string format = "PDF";
string encoding = null;
string mimeType = null;
string extension = null;
REWebService.Warning[] warnings = null;
string[] streamIDs = null;
string _reportName = #"/FIMO GOF Assets Reports/PURCHASE ORDER";
REWebService.ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID);
REWebService.ParameterValue[] parameters = new REWebService.ParameterValue[4];
parameters[0] = new REWebService.ParameterValue();
parameters[0].Name = "MVDI_ID";
parameters[0].Value = lblVendid.Text;
parameters[1] = new REWebService.ParameterValue();
parameters[1].Name = "MBRI_ID";
parameters[1].Value = lblBranch.Text;
parameters[2] = new REWebService.ParameterValue();
parameters[2].Name = "MPDI_Date";
parameters[2].Value = lblDate.Text;
parameters[3] = new REWebService.ParameterValue();
parameters[3].Name = "ReportParameter1";
parameters[3].Value = lblPOId.Text;
rsExec.SetExecutionParameters(parameters, "en-us");
Sendresults = rsExec.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
MemoryStream ms = new MemoryStream(Sendresults);
//To create a PDF
if (format == "PDF")
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", "inline;filename=output.pdf");
Response.AddHeader("Content-Length", Sendresults.Length.ToString());
}
Response.OutputStream.Write(Sendresults, 0, Sendresults.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
}
catch(Exception Ex)
{
throw Ex;
}
}
You can use URL access, as described here: http://msdn.microsoft.com/en-us/library/ms154040(v=sql.105).aspx
http://<Server Name>/reportserver?/Sales/YearlySalesSummary&rs:Format=PDF&rs:Command=Render