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?
Related
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.
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:
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;
}
I tried to insert image into RichTextBox by clicking the button.
I referred this post - How can I insert an image into a RichTextBox? and made the source code
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "BMP (*.bmp)|*.bmp|JPEG (*.jpg, *.jpeg, *.jpe, *.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|GIF (*.gif)|*.gif|PNG (*.png)|*.png|All files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.png";
if (f.ShowDialog() == DialogResult.OK)
{
// Get type of the file
string typeOfFile = "";
Stack<char> typeParse = new Stack<char>();
int pointer = f.FileName.Length - 1
while (pointer > 0 && f.FileName[pointer] != '.')
typeParse.Push(f.FileName[pointer--]);
while (typeParse.Count > 0)
typeOfFile += typeParse.Pop();
typeOfFile = typeOfFile.ToLower();
// Convert Image to byte[]
Image image = Image.FromFile(f.FileName);
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
// Insert the image data in RichTextBox which is converted to hex from byte[]
// by using BitConverter.ToString(ms.ToArray();
StringBuilder imageRTF = new StringBuilder();
imageRTF.Append(#"{\pict\" + typeOfFile + #"blip\picw" + image.Width + #"\pich" + image.Height);
imageRTF.Append(#"\picwgoal" + image.Width + #"\pichgoal" + image.Height);
imageRTF.Append(#" " + BitConverter.ToString(ms.ToArray()) + #"}");
string rtf1 = richTextBox1.Rtf.Trim().TrimEnd('}');
string rtf2 = imageRTF.ToString();
richTextBox1.Rtf = rtf1 + rtf2;
}
}
but when I executed and opened png file, only one line break was inserted in RichTextBox..
What is wrong??
Is it possible to send to an html a memorystream, like a file?
The idea is not creating a file in the hard drive.
I have created the stream and I can donwload the file no problem, the problem is passing to the variable to send to the aspx page so I can use it to show the file on a particulary div.
Is it possible? without creating a file in the disk.
Best Regards and Thanks
this is the Code i have:
public string ExportMemoryPdf(DataTable dtpdf, String Path)
{
string User = System.Web.HttpContext.Current.User.Identity.Name.ToString();
string Date = DateTime.Now.ToString();
string Year = DateTime.Now.ToString("yyyy");
string Month = DateTime.Now.ToString("MM");
string Day = DateTime.Now.ToString("dd");
string Hour = DateTime.Now.ToString("hh");
string Minutes = DateTime.Now.ToString("mm");
string Seconds = DateTime.Now.ToString("ss");
string FileName = User + Day + Month + Year + Hour + Minutes + Seconds;
//Session["WhereIsIt"].ToString()
//-----------------------Chamada de Classe de Registo de Eventos--------------------------
//string Message = "The User Asked For a PDF File From the Table" + Request.QueryString["Position"] + "With the Filename: " + FileName;
string Message = "The User Asked For a PDF File From the Table With the Filename: " + FileName;
//OneGrid.ExportSettings.IgnorePaging = true;
//OneGrid.Rebind();
//RegisterFile.AddRegistry(User, Message, "Message");
//------------------------------ Variaveis para aceder a Tabela --------------------------
int columncount = dtpdf.Columns.Count;
int rowcount = dtpdf.Rows.Count;
//-------------------------------Iniciaçao de criação do documento -----------------------
Document pdf1 = new Document(PageSize.A4_LANDSCAPE.Rotate());
using (MemoryStream output = new MemoryStream())
{
pdf1.SetMargins(0, 0, 80, 50);
iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 10);
//----------------------------------Preparação da Tabela ---------------------------------
PdfPTable table = new PdfPTable(columncount);
//-----------------------------------Criação de Ficheiro ---------------------------------
string path = System.Web.HttpContext.Current.Server.MapPath(Path);
//string path = System.IO.Path.GetTempPath();
//Label1.Text = path.ToString();
//PdfWriter pdfWriter = PdfWriter.GetInstance(pdf1, new FileStream(path + "/" + FileName + ".pdf", FileMode.Create));
PdfWriter pdfWriter = PdfWriter.GetInstance(pdf1, output);
//----------------------------------- Dimensões da Tabela ---------------------------------------
table.WidthPercentage = 90;
//-------------------------------Criação do Header e Footer de cada folha-------------------------
KIOSK.Classes.Header_Footer page = new Classes.Header_Footer();
//-----------------------------------Inserção de conteudos -------------------------------
pdfWriter.PageEvent = page;
pdf1.Open();
//table.AddCell(HttpContext.Current.Request.QueryString["position"].ToString());
for (int z = 0; z < columncount; z++)
{
var sabersenao = dtpdf.Columns[z].ToString();
table.AddCell(new Phrase(sabersenao, font20));
}
for (int u = 0; u < rowcount; u++)
{
int contador = 0;
while (contador < columncount)
{
var CamposCorrigidos = dtpdf.Rows[u].ItemArray[contador].ToString();
StringBuilder ConvPassword = new StringBuilder(CamposCorrigidos);
ConvPassword.Replace("&", string.Empty);
ConvPassword.Replace(" ", string.Empty);
string CamposCorrigidos2 = ConvPassword.ToString();
table.AddCell(new Phrase(CamposCorrigidos2, font20));
contador += 1;
}
}
//----------------------Abertura/Fecho e inserção do componentes necessrios ao pdf---------
pdf1.Add(table);
pdf1.Close();
//System.Web.HttpContext.Current.Response.ClearContent();
//System.Web.HttpContext.Current.Response.ClearHeaders();
//System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
//System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
//System.Web.HttpContext.Current.Response.BinaryWrite(output.ToArray());
//System.Web.HttpContext.Current.Response.End();
//System.Web.HttpContext.Current.Response.Flush();
//System.Web.HttpContext.Current.Response.Clear();
//System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
//System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "PdfViewer; filename=" + FileName +".PDF");
////System.Web.HttpContext.Current.Response.AddHeader("content-length", output.Length.ToString());
//System.Web.HttpContext.Current.Response.BinaryWrite(output.ToArray());
//System.Web.HttpContext.Current.Response.End();
//output.Read(pdfByte, 0, (int)pdfByte.Length);
output.Read(pdfByte, 0, (int)pdfByte.Length);
var strBase64 = Convert.ToBase64String(pdfByte);
}
return Convert.ToBase64String(pdfByte);
}
and the error:
Cannot access a closed Stream.
thansk
If you know the content type the memorystream will return, you can read the stream to a variable which handles that type and then process that.
for an example with a String, see How do you get a string from a MemoryStream?. they write a string to a memorystream and then read it back out again.
It's possible, you will have to convert your memorystream to an array of bytes. Then you will have to convert your array of bytes to a Base64 string. And finally you will have to put that base64 string into your img src
An explanation about base64 to image in html.
Take notice that this will work for images. Any other files won't work as since those files need to be downloaded and thus need to have a physical location. Unless you plan on writing a javascript handler for the filetypes you which to show.
Update:
For pdf's you can do the following, however it might not be crossbrowser compatible.
CodeBehind
//string filepath = Server.MapPath("/Temp.pdf");
byte[] pdfByte; //= Helper.GetBytesFromFile(filepath);
using(var stream = ....) {
stream.read(pdfByte,0,(int)pdfByte.length);
var strBase64=Convert.ToBase64String(pdfByte);
HTML
<object data=",<<yourBase64StringHereWithoutthesmallerthenbiggerthenquotes==>>" type="application/pdf" width="800px"></object>
Updated your code:
public string ExportMemoryPdf(DataTable dtpdf, String Path)
{
string User = System.Web.HttpContext.Current.User.Identity.Name.ToString();
string Date = DateTime.Now.ToString();
string Year = DateTime.Now.ToString("yyyy");
string Month = DateTime.Now.ToString("MM");
string Day = DateTime.Now.ToString("dd");
string Hour = DateTime.Now.ToString("hh");
string Minutes = DateTime.Now.ToString("mm");
string Seconds = DateTime.Now.ToString("ss");
string FileName = User + Day + Month + Year + Hour + Minutes + Seconds;
Request.QueryString["Position"] + "With the Filename: " + FileName;
string Message = "The User Asked For a PDF File From the Table With the Filename: " + FileName;
int columncount = dtpdf.Columns.Count;
int rowcount = dtpdf.Rows.Count;
Document pdf1 = new Document(PageSize.A4_LANDSCAPE.Rotate());
pdf1.SetMargins(0, 0, 80, 50);
iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 10);
PdfPTable table = new PdfPTable(columncount);
string path = System.Web.HttpContext.Current.Server.MapPath(Path);
table.WidthPercentage = 90;
KIOSK.Classes.Header_Footer page = new Classes.Header_Footer();
for (int z = 0; z < columncount; z++)
{
var sabersenao = dtpdf.Columns[z].ToString();
table.AddCell(new Phrase(sabersenao, font20));
}
for (int u = 0; u < rowcount; u++)
{
int contador = 0;
while (contador < columncount)
{
var CamposCorrigidos = dtpdf.Rows[u].ItemArray[contador].ToString();
StringBuilder ConvPassword = new StringBuilder(CamposCorrigidos);
ConvPassword.Replace("&", string.Empty);
ConvPassword.Replace(" ", string.Empty);
string CamposCorrigidos2 = ConvPassword.ToString();
table.AddCell(new Phrase(CamposCorrigidos2, font20));
contador += 1;
}
}
var base64String = string.Empty;
using (MemoryStream output = new MemoryStream())
{
PdfWriter pdfWriter = PdfWriter.GetInstance(pdf1, output);
pdfWriter.PageEvent = page;
pdf1.Open();
pdf1.Add(table);
pdf1.Close();
bytes = output.ToArray();
var base64String = Convert.ToBase64String(bytes);
}
return base64String;
}