Its posible open print dialog when is open in memorystram?
Actually I save the pdf in "~/App_Data/Rep_PDF/" and after show a pdf in an iframe but I cant do it because I recive a message :
"Not allowed to load local resource: file:///C:/Users/andres.martinez/Documents/TFS%20Monterrey%20Gob/InterfaceMonterrey%20PROD/Interface%20Monterrey%20PROD/InterfaceMonterrey/App_Data/Rep_PDF/Copia_C_Administrativa%2030-04-2019.pdf"
Could you help me How to print a pdf in asp mvc?
this is part of my code:
public ActionResult ImprimeReporte()
{
//Indicamos donde vamos a guardar el documento
string directorioRaiz = "~/App_Data/Rep_PDF/";
string NombreArchivoPDF = "C_Administrativa " + DateTime.Today.ToString("dd-MM-yyyy") + ".pdf";
string path_Original=Server.MapPath(directorioRaiz+NombreArchivoPDF);
string path_Copia = Server.MapPath(directorioRaiz + "Copia_"+NombreArchivoPDF);
if (System.IO.File.Exists(path_Original))
{
//SI EXISTE EL ARCHIVO EN LA CARPETA, LO MANDA A IMPRIMIR
Inicia_PrintScript(path_Original, path_Copia);
ViewData["path_Copia"] = path_Copia;
//Elimina los archivos , despues de que se imprimio
// System.IO.File.Delete(path_Original);
//System.IO.File.Delete(path_Copia);
}
else
{
//SI NO EXISTE MANDA LLAMAR AL METODO PARA DESCARGAR EL ARCHIVO Y DESPUES IMPRIMIRLO
Genera_Pdf_Administrativo();
Inicia_PrintScript(path_Original, path_Copia);
ViewData["path_Copia"] = path_Copia;
//Elimina los archivos , despues de que se imprimio
//System.IO.File.Delete(path_Original);
//System.IO.File.Delete(path_Copia);
}
return View();
}
second part
public static void Inicia_PrintScript(string Original, string Copia)
{
PdfReader reader = new PdfReader(Original);
PdfStamper stamper = new PdfStamper(reader, new FileStream(Copia, FileMode.Create));
AcroFields fields = stamper.AcroFields;
stamper.JavaScript = "this.print(true);\r";
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
View
<iframe src="#ViewData["path_Copia"].ToString()" id="myFrame" frameborder="0" style="border:0;" width="700" height="300"></iframe>
Well, it's possible to open a PDF with print dialog in another tab.
In your controller you need to get the file in memory just to return it, or generate the file on fly.
public FileResult PDFToReturn()
{
string filePath = Server.MapPath("Path_to_PDF");
return File(System.IO.File.ReadAllBytes(filePath), System.Web.MimeMapping.GetMimeMapping(filePath));
}
javascript does the magic.
function printPDF() {
let link = 'javascript:w=window.open("/Controller/PDFToReturn"); w.print();';
location.href = link;
}
Related
I can't log a string from an HTTP request using NLOG. Here's the code:
HttpResponseMessage res = client.PostAsync(path, content).Result;
if (!res.IsSuccessStatusCode)
{
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
String responseStr = res.Content.ReadAsStringAsync().Result;
//TODO(nassim) : Remplacé ce try catch par juste un retour d'erreur dans les log
//ErrorReponse error = JsonConvert.DeserializeObject<ErrorReponse>(responseStr);
Logger.Debug("Taille du log : " + responseStr.Length);
if(responseStr.Length > 200)
{
Logger.Debug(" 1");
Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 200));
}
else
{
Logger.Debug(" 2");
Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 10));
}
if (responseStr.Contains("Invalid credentials.") || responseStr.Contains("Token is expired."))
{
refreshToken(vault, storedValues);
storeDocInReciTAL(env);
}
throw new Exception("Erreur d'envoi du document vers reciTAL.");
And here's the stacktrace:
As you can see, the line concatening with the responseStr doesn't show anywhere. At first I thought it was because the string was too long, but it's only 37 characters.
What am I doing wrong?
Using structured logging resolves the problem. I don't understand why it doesn't work with a simple concatenation.
im trying in c# to merge 2 pdf in a single one using the pdfsharp library, it shows an error that it couldnt find the path in the path where im going to save it, this is where i put my paths
string directorio = #"C:\Users\Usuario\Documents\PDF\";//Directorio donde buscara los archivos pdf
string destino = #"C:\Users\Usuario\Documents\Prueba\";//Directorio donde estara el archivo unido
string[] archivo = Directory.GetFiles(directorio);
Unir(destino, archivo);
if (MessageBox.Show("Espere un momento mientras su solicitud es procesada", "INFORMACION" + MessageBoxButtons.OK + MessageBoxIcon.Information) == DialogResult.OK)
{
MessageBox.Show("Su documento se ha unido con exito, fue enviado a la direccion: " + destino);
}
this is where my merge method
private void Unir(string outfilePath , string[] pdfFiles){
PdfDocument documento = new PdfDocument();
foreach(string pdfFile in pdfFiles)
{
PdfDocument inputDocumento = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
documento.Version = inputDocumento.Version;
foreach(PdfPage page in inputDocumento.Pages)
{
documento.AddPage(page);
}
documento.Options.CompressContentStreams = true;
documento.Options.NoCompression = false;
documento.Save(outfilePath);
}
}
A file name is needed to save a PDF file, not a folder.
The Save should be made after the foreach loop to save only once.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
//English
Im newbie coding... i want to edit some text files in this path D:.
The problem is if one text file has been used my app throw error saying "Access Denied"...
I want to skip that error and continue with the next file... help me please...
Suppose the file United3.txt throw access denied and i cant edit.
//Español
Soy nuevo programador y quiero editar varios archivos de texto en un disco duro D.
El problema es que si uno esta siendo usado me dice acceso denegado por ende quiero omitir la edicion a el y que siga con el proximo archivo.
Este es mi método.
public void startAction3()
{
string DiscoDuroD = "D:\\";
if (Directory.Exists(DiscoDuroD))
{
string text = "Hello My Friend";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United3.txt"), true))
{
outputFile.WriteLine(text);
}
string text2 = "EYY";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United4.txt"), true))
{
outputFile.WriteLine(text);
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco Duro D no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
(Hola GBY)
You should capture Exception and proceed with the next file.
Find below an example.
More info about try-catch structure --> https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/keywords/try-catch
De nada!
public void startAction3()
{
string DiscoDuroD = "D:\\";
if (Directory.Exists(DiscoDuroD))
{
string text = "Hello My Friend";
try
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United3.txt"), true))
{
outputFile.WriteLine(text);
}
}
catch (IOException ex)
{
// do something in case any error occurs, leave a trace or write a console warning...
console.WriteLine("Error fichero United3: "+ ex.Message)
}
string text2 = "EYY";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United4.txt"), true))
{
outputFile.WriteLine(text);
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco Duro D no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
Perdon por la falta de puntuacion y cualquier error de espanol. Hace un tiempo sin usar espanol con regularidad.
Sorry for the lack of punctuation and mistakes in my Spanish. It's been a while since I used Spanish regularly.
Si tu programa tiene que procesar varios archivos en una manera igual, podrias implementar un metodo asi con 'try-catch' igual que el respuesta de David:
If your application has to process several files in a similar way, you could implement a method like this with a 'try-catch' block similar to David's answer:
public void OutputToFile(string discPrefix, string fileName, string text)
{
if (Directory.Exists(discPrefix))
{
try
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(discPrefix,
fileName), true))
{
outputFile.WriteLine(text);
}
}
catch (IOException ex)
{
// do something in case any error occurs, leave a trace or write a console warning...
console.WriteLine("Error fichero" + fileName + ": " + ex.Message)
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
...y usarlo entre StartAction3 asi:
...and call it from within your StartAction3 like this:
OutputToFile("D://", "United3.txt", "Hello my friend");
OutputToFile("D://", "United4.txt", "EYY");
Can anybody give me a hand, i am traying to create a pdf file who has a table of employees inside, i get the employee data form a database, so the table could be occupied one o serveral pages of the document.
I set the margin of the table
table.SetMarginTop(100);
table.SetMarginBottom(20);
But as soon the employee data generates another page of the pdf documetn the margins get lost
Here is my complete code of how i am generating the pdf and some screenshots
internal bool CreatePdfInspectorDelegates(string storeName, DateTimePicker date, string inspector, DataTable delegateStoreDT, DataTable delegateEmployeeDT)
{try
{
string auxPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
auxPath = auxPath + #"\PDF\Creados\notifacionInspectorDelegados" + storeName + ".pdf";
PdfWriter writer = new PdfWriter(auxPath);
PageSize ps = PageSize.LETTER;
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf, ps);
//Fuentes de texto
PdfFont fontNormal = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont fontBold = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD);
//Datos
string dateIn = String.Format("Fecha{0}", date.Value.ToString("dd/MM/yyyy"));
string instpector = String.Format("{0}", date.Value.ToString("dd/MM/yyyy"));
//Cuerpo
Paragraph pTittel = new Paragraph();
pTittel.SetPaddingTop(70);
pTittel.SetFixedLeading(25);
Text text = new Text("NOTIFICACIÓN AL INSPECTOR O INSPECTORA DEL TRABAJO\n DE LA VOLUNTAD DE LOS TRABAJADORES Y LAS TRABAJADORAS\n DE ELEGIR A LOS DELEGADOS Y A LAS DELEGADAS DE PREVENCIÓN").SetFont(fontBold).SetTextAlignment(TextAlignment.CENTER);
pTittel.SetTextAlignment(TextAlignment.CENTER);
pTittel.Add(text);
Paragraph pBody = new Paragraph();
pBody.SetFixedLeading(22);
Text text2 = new Text("\nFecha: ").SetFont(fontNormal);
Text textDate = new Text(date.Value.ToString("dd/MM/yyyy")).SetFont(fontNormal).SetUnderline();
Text text3 = new Text("\n\nCiudadano(a):\n").SetFont(fontNormal);
Text textInspector = new Text(inspector).SetFont(fontNormal).SetUnderline();
Text text4= new Text("\n\nNosotros, los(as) trabajadores(as), en cumplimiento a lo señalado en el artículo 41 de la Ley Orgánica de Prevención, Condiciones y Medio Ambiente de Trabajo(Lopcymat) y del artículo 58 de su Reglamento Parcial, nos dirigimos a Usted con el objeto de manifestarle nuestra voluntad de elegir a los Delegados y / o Delegadas de Prevención correspondientes a la entidad de trabajo: ").SetFont(fontNormal);
Text textCenter = new Text("GRUPO TOTAL 99 C.A.").SetFont(fontBold).SetUnderline();
Text text5 = new Text(" cuya dirección es: ").SetFont(fontNormal);
Text textCenterAddress = new Text("CALLE LAS VEGAS CRUCE CON SOLEDAD EDIFICIO CLARIANT VENEZUELA, ZONA INDUSTRIAL DE LA TRINIDAD, CARACAS. ").SetFont(fontNormal).SetUnderline();
Text text6 = new Text(" , específicamente los correspondientes al centro de trabajo: ").SetFont(fontNormal);
Text textBranch = new Text(GetStoreBranch(delegateStoreDT).ToUpper()).SetFont(fontNormal).SetUnderline();
Text text7 = new Text(" , ubicado en: ").SetFont(fontNormal);
Text textBranchAddress = new Text(GetStoreAddress1(delegateStoreDT).ToUpper() + ", " + GetStoreAddress2(delegateStoreDT).ToUpper()).SetFont(fontNormal).SetUnderline();
Text text8 = new Text("\n\nNotificación que se hace para efectos del artículo 59 del Reglamento Parcial de la Ley Orgánica de Prevención, Condiciones y Medio Ambiente de Trabajo(RLopcymat).\n\nA continuación firman los(as) trabajadores(as) solicitantes:\n").SetFont(fontNormal);
pBody.Add(text2);
pBody.Add(textDate);
pBody.Add(text3);
pBody.Add(textInspector);
pBody.Add(text4);
pBody.Add(textCenter);
pBody.Add(text5);
pBody.Add(textCenterAddress);
pBody.Add(text6);
pBody.Add(textBranch);
pBody.Add(text7);
pBody.Add(textBranchAddress);
pBody.Add(text8);
pBody.SetTextAlignment(TextAlignment.JUSTIFIED);
doc.Add(pTittel);
doc.Add(pBody);
//Segunda pagina
doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
//Empleados
float[] columnWidths = { 5, 5, 5, 5, 4 };
Table table = new Table(UnitValue.CreatePercentArray(columnWidths));
table.SetWidth(UnitValue.CreatePercentValue(100));
Cell[] header =
{
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Nombres y Apeliidos").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Cedula\nIdentidad N°").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Cargo Actual").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Firma").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Huella").SetTextAlignment(TextAlignment.CENTER).SetBold())
};
foreach (Cell cells in header)
{
table.AddCell(cells);
}
foreach (DataRow row in delegateEmployeeDT.Rows)
{
if (row[0].ToString() == "True")
{
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[2].ToString().ToUpper() + "\n" + row[3].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[4].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[5].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph("")));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph("")));
}
}
table.SetMarginTop(100);
table.SetMarginBottom(20);
doc.Add(table);
doc.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
Top and bottom margins are not supposed to be applied to parts of the table that breaks across several pages. They only define space between previous element and current one (top margin) and between current element and next one (bottom margin).
If you want to preserve spacing on top of a table when it splits across pages you can use header and footer functionality. Table headers and footers are repeated on each page occupied by a table, and you can add a cell without borders with fixed height which will result in spacing on each page. Here is an example:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
Document doc = new Document(pdfDoc, PageSize.A4.rotate());
doc.add(new Paragraph("Starting text"));
Table table = new Table(UnitValue.createPercentArray(5)).useAllAvailableWidth();
table.addHeaderCell(new Cell(1, 5).setHeight(100).setBorder(Border.NO_BORDER));
table.addHeaderCell(new Cell(1, 5).
add(new Paragraph("Header")));
table.addFooterCell(new Cell(1, 5).
add(new Paragraph("Footer")));
table.addFooterCell(new Cell(1, 5).setHeight(100).setBorder(Border.NO_BORDER));
for (int i = 0; i < 350; i++) {
table.addCell(new Cell().add(new Paragraph(String.valueOf(i + 1))));
}
doc.add(table);
doc.close();
Here is what the result looks like:
I'm getting some images from my database and populating a ppt file with them like this:
foreach (DataRow item in imagens.Rows)
{
nomeArquivo = item[0].ToString();
imagebytes = (byte[])item[1];
extensao = item[2].ToString();
MemoryStream ms = new MemoryStream(imagebytes);
img = Image.FromStream(ms);
img.Save(nomeArquivo + ".png", ImageFormat.Png);
slideAdd = slides.Add(indice, PowerPoint.PpSlideLayout.ppLayoutPictureWithCaption);//no objeto de slides, vou criar um no índice especificado - começa a partir de 1
shape = slideAdd.Shapes[2];
string caminho = Path.Combine(executableLocation, nomeArquivo + ".png");
slideAdd.Shapes.AddPicture2(caminho, MsoTriState.msoFalse, MsoTriState.msoTrue, shape.Left, shape.Top, shape.Width, shape.Height, MsoPictureCompress.msoPictureCompressFalse);
slideAdd.Shapes[1].TextFrame.TextRange.Text = nomeArquivo;
slideAdd.Shapes[3].TextFrame.TextRange.Text = nomeArquivo;
indice++;
}
However, they are not resized to fit the containg shape:
Is there a way to resize them beforehand?