//*** une los archivos, está actualmente aplicado public static void MergePDF(string src, string src1, string final) { //altotal 856 float y = -302; final = Properties.Settings.Default.PathDefecto + @"generadasfacturas\" + final; PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileStream(final, FileMode.Create)); PdfContentByte canvas = stamper.GetUnderContent(1); PdfReader r; PdfImportedPage page; PdfReader s_reader = new PdfReader(src1); Rectangle pageSize = reader.GetPageSize(1); int n = reader.NumberOfPages; for (int i = 1; i <= n; i++) { r = new PdfReader(src1); page = stamper.GetImportedPage(r, 1); canvas.AddTemplate(page, 0, y); stamper.Writer.FreeReader(r); r.Close(); } stamper.Close(); }
public static void StampPdfWithTemplate(string fileName) { var backgroundPath = fileName; const string original = @"Avery5167Template.pdf"; var directoryName = Path.GetDirectoryName(fileName); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var extension = Path.GetExtension(fileName); var resultFileName = $"{fileNameWithoutExtension}WithTemplate{extension}"; var result = Path.Combine( directoryName ?? throw new InvalidOperationException(), resultFileName); var originalReader = new PdfReader(original); var backgroundReader = new PdfReader(backgroundPath); var stamper = new PdfStamper(originalReader, new FileStream(result, FileMode.Create)); var page = stamper.GetImportedPage(backgroundReader, 1); var numberOfPages = originalReader.NumberOfPages; for (var currentPage = 1; currentPage <= numberOfPages; currentPage++) { var background = stamper.GetUnderContent(currentPage); background.AddTemplate(page, 0, 0); } stamper.Close(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src * @param src the original PDF * @param stationery the resulting PDF */ public byte[] ManipulatePdf(byte[] src, byte[] stationery) { ColumnText ct = new ColumnText(null); string SQL = @"SELECT country, id FROM film_country ORDER BY country "; using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { ct.AddElement(new Paragraph( 24, new Chunk(r["country"].ToString()) )); } } } } // Create a reader for the original document and for the stationery PdfReader reader = new PdfReader(src); PdfReader rStationery = new PdfReader(stationery); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Create an imported page for the stationery PdfImportedPage page = stamper.GetImportedPage(rStationery, 1); int i = 0; // Add the content of the ColumnText object while (true) { // Add a new page stamper.InsertPage(++i, reader.GetPageSize(1)); // Add the stationary to the new page stamper.GetUnderContent(i).AddTemplate(page, 0, 0); // Add as much content of the column as possible ct.Canvas = stamper.GetOverContent(i); ct.SetSimpleColumn(36, 36, 559, 770); if (!ColumnText.HasMoreText(ct.Go())) { break; } } } return(ms.ToArray()); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create a reader for the original document PdfReader reader = new PdfReader(src); // Create a reader for the advertisement resource PdfReader ad = new PdfReader(RESOURCE); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Create the advertisement annotation for the menubar Rectangle rect = new Rectangle(400, 772, 545, 792); PushbuttonField button = new PushbuttonField( stamper.Writer, rect, "click" ); button.BackgroundColor = BaseColor.RED; button.BorderColor = BaseColor.RED; button.FontSize = 10; button.Text = "Close this advertisement"; button.Image = Image.GetInstance( Path.Combine(Utility.ResourceImage, IMAGE) ); button.Layout = PushbuttonField.LAYOUT_LABEL_LEFT_ICON_RIGHT; button.IconHorizontalAdjustment = 1; PdfFormField menubar = button.Field; String js = "var f1 = getField('click'); f1.display = display.hidden;" + "var f2 = getField('advertisement'); f2.display = display.hidden;" ; menubar.Action = PdfAction.JavaScript(js, stamper.Writer); // Add the annotation stamper.AddAnnotation(menubar, 1); // Create the advertisement annotation for the content rect = new Rectangle(400, 550, 545, 772); button = new PushbuttonField( stamper.Writer, rect, "advertisement" ); button.BackgroundColor = BaseColor.WHITE; button.BorderColor = BaseColor.RED; button.Text = "Buy the book iText in Action 2nd edition"; button.Template = stamper.GetImportedPage(ad, 1); button.Layout = PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM; PdfFormField advertisement = button.Field; advertisement.Action = new PdfAction( "http://www.1t3xt.com/docs/book.php" ); // Add the annotation stamper.AddAnnotation(advertisement, 1); } return(ms.ToArray()); } }
public static void AddTextWatermark(string sourceFilePath, string watermarkTemplatePath, string targetFilePath) { var pdfReaderSource = new PdfReader(sourceFilePath); var pdfStamper = new PdfStamper(pdfReaderSource, new FileStream(targetFilePath, FileMode.Create)); var pdfReaderTemplate = new PdfReader(watermarkTemplatePath); var page = pdfStamper.GetImportedPage(pdfReaderTemplate, 1); for (var i = 0; i < pdfReaderSource.NumberOfPages; i++) { var content = pdfStamper.GetUnderContent(i + 1); content.AddTemplate(page, 0, 0); } pdfStamper.Close(); pdfReaderTemplate.Close(); }
//Add Company Letter-Head/Stationary to an existing pdf private void AddCompanyStationary() { PdfReader reader = new PdfReader(Server.MapPath(P_InputStream2)); PdfReader s_reader = new PdfReader(Server.MapPath(P_InputStream4)); using (PdfStamper stamper = new PdfStamper(reader, new FileStream(Server.MapPath(P_OutputStream), FileMode.Create))) { PdfImportedPage page = stamper.GetImportedPage(s_reader, 1); int n = reader.NumberOfPages; PdfContentByte background; for (int i = 1; i <= n; i++) { background = stamper.GetUnderContent(i); background.AddTemplate(page, 0, 0); } stamper.Close(); } }
static void ManipulatePdf(String src, String stationery, String dest) { // Create readers PdfReader reader = new PdfReader(src); PdfReader sReader = new PdfReader(stationery); // Create the stamper PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // Add the stationery to each page PdfImportedPage page = stamper.GetImportedPage(sReader, 1); int n = reader.NumberOfPages; PdfContentByte background; for (int i = 1; i <= n; i++) { background = stamper.GetUnderContent(i); background.AddTemplate(page, 0, 0); } // CLose the stamper stamper.Close(); }
public static bool InsertPages(string sourcePdf, string insertPdf, int pagenumber) { //variables //String first_source = "D:/myprogram/pdf/htmlpdf.pdf"; //String second_source = "d:/pdfcontentadded.pdf"; string pathout = Guid.NewGuid().ToString() + ".pdf"; //@"C:\doMain.Utils\inDigitalization\pdfout.pdf"; //create a document object //var doc = new Document(PageSize.A4); //create PdfReader objects to read pages from the source files PdfReader reader = new PdfReader(insertPdf); PdfReader reader1 = new PdfReader(sourcePdf); //create PdfStamper object to write to the pages read from readers PdfStamper stamper = new PdfStamper(reader1, new FileStream(pathout, FileMode.Create)); //get one page from htmlpdf.pdf PdfImportedPage page = stamper.GetImportedPage(reader, 1); //the page gotten from htmlpdf.pdf will be inserted at the second page in the first source doc stamper.InsertPage(pagenumber, reader1.GetPageSize(1)); //insert the page PdfContentByte pb = stamper.GetUnderContent(pagenumber); pb.AddTemplate(page, 0, 0); //close the stamper stamper.Close(); reader.Close(); reader1.Close(); reader.Dispose(); reader1.Dispose(); FileUtils.Delete(sourcePdf, true); FileUtils.CopyBlocking(pathout, sourcePdf); FileUtils.Delete(pathout); return(true); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param stationery a PDF that will be added as background */ public byte[] ManipulatePdf(byte[] src, byte[] stationery) { // Create readers PdfReader reader = new PdfReader(src); PdfReader s_reader = new PdfReader(stationery); using (MemoryStream ms = new MemoryStream()) { // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add the stationery to each page PdfImportedPage page = stamper.GetImportedPage(s_reader, 1); int n = reader.NumberOfPages; PdfContentByte background; for (int i = 1; i <= n; i++) { background = stamper.GetUnderContent(i); background.AddTemplate(page, 0, 0); } } return(ms.ToArray()); } }
public void SetBackground(string pdfFile, Stream stream, Drawing.Image image, int type = 0) { PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(pdfFile); stamper = new PdfStamper(reader, stream); var totalPage = reader.NumberOfPages; for (int current = 1; current <= totalPage; current++) { var canvas = stamper.GetUnderContent(current); var page = stamper.GetImportedPage(reader, current); var img = Image.GetInstance(image, Drawing.Imaging.ImageFormat.Png); switch (type) { case 1: //top left img.SetAbsolutePosition(0, page.Height - img.Height); canvas.AddImage(img); break; case 2: //top center img.SetAbsolutePosition((page.Width - img.Width) / 2, page.Height - img.Height); canvas.AddImage(img); break; case 3: //top right img.SetAbsolutePosition(page.Width - img.Width, page.Height - img.Height); canvas.AddImage(img); break; case 4: //middle left img.SetAbsolutePosition(0, (page.Height - img.Height) / 2); canvas.AddImage(img); break; case 5: //middle center img.SetAbsolutePosition((page.Width - img.Width) / 2, (page.Height - img.Height) / 2); canvas.AddImage(img); break; case 6: //middle right img.SetAbsolutePosition(page.Width - img.Width, (page.Height - img.Height) / 2); canvas.AddImage(img); break; case 7: //bottom left img.SetAbsolutePosition(0, 0); canvas.AddImage(img); break; case 8: //bottom center img.SetAbsolutePosition((page.Width - img.Width) / 2, 0); canvas.AddImage(img); break; case 9: //bottom right img.SetAbsolutePosition(page.Width - img.Width, 0); canvas.AddImage(img); break; default: //平扑 int xRepeats = (int)((page.Width + img.Width - 1) / image.Width); int yRepeats = (int)((page.Height + img.Height - 1) / image.Height); for (int i = 0; i < xRepeats; i++) { for (int j = 0; j < yRepeats; j++) { img.SetAbsolutePosition(img.Width * i, image.Height * j); canvas.AddImage(img); } } break; } //img.SetAbsolutePosition(120, 120); //canvas.AddImage(img); //ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("Hello people!"), 36, 540, 0); OnProgress(current, totalPage); } stamper.Close(); } catch (Exception ex) { OnError(ex); } finally { stamper.Close(); reader.Close(); } OnFinish(); }
public static void SignHashed(MemoryStream Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, Image img, int nroHojaFirma, string path, float h, string att_1, string att_2, string att_3, string url_terminos) { try { X509CertificateParser objCP = new X509CertificateParser(); X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1"); PdfReader objReader = new PdfReader(Source); //string[] msg = Certificate.SubjectName.Name.Split(','); //Document document = new Document(PageSize.A4, 50, 50, 150, 100); //PdfWriter pdfwritter = PdfWriter.GetInstance(document, new FileStream("C:\\Users\\Public\\terminos_condiciones.pdf", FileMode.OpenOrCreate)); using (PdfReader readerTerm = new PdfReader(url_terminos)) using (MemoryStream workStream = new MemoryStream()) { PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.OpenOrCreate, FileAccess.Write), '\0'); int nroPages = objReader.NumberOfPages + 1; Rectangle rectangle = readerTerm.GetPageSize(1); objStamper.InsertPage(nroPages, rectangle); PdfImportedPage bg = objStamper.GetImportedPage(readerTerm, 1); objStamper.GetUnderContent(nroPages).AddTemplate(bg, 0, 0); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; img.ScaleAbsolute(120f, 60f); img.SetAbsolutePosition(0, 28); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); BaseFont bfBold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false); if (true) { objSA.SetVisibleSignature(new Rectangle(50, h - 120, 200, h), nroHojaFirma, "Firma Digital emitida por el sistema BV Digital"); } PdfTemplate n2Layer = objSA.GetLayer(2); n2Layer.BeginText(); n2Layer.SetFontAndSize(bfBold, 7); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Inspectorate Services Perú S.A.C", 0, 100, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "A Bureau Veritas Group Company", 0, 90, 0); n2Layer.EndText(); n2Layer.AddImage(img); n2Layer.BeginText(); n2Layer.SetFontAndSize(bf, 7); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Firmado Digitalmente por", 0, 40, 0); //string user = msg[2].Substring(msg[2].IndexOf('=') + 1); //user += " " + msg[3].Substring(msg[3].IndexOf('=') + 1); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_3, 0, 30, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Fecha: " + objSA.SignDate.ToString(), 0, 20, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_1, 0, 10, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_2, 0, 0, 0); n2Layer.EndText(); objSA.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; MakeSignature.SignDetached(objSA, externalSignature, objChain, null, null, null, 0, CryptoStandard.CMS); objStamper.SetFullCompression(); } } catch (Exception e) { Utility.log_err.save(null, e); } }
private void DoAddBackground(PdfStamper stamper, ConversionProfile profile) { if (!profile.BackgroundPage.Enabled) { return; } Logger.Debug("Start adding background."); var nFile = stamper.Reader.NumberOfPages; var backgroundPdfReader = new PdfReader(profile.BackgroundPage.File); //ExtractPages(profile.BackgroundPage.File); //new PdfReader(profile.BackgroundPage.File); Logger.Debug("BackgroundFile: " + Path.GetFullPath(profile.BackgroundPage.File)); var nBackground = backgroundPdfReader.NumberOfPages; int numberOfFrontPagesWithoutBackground; try { numberOfFrontPagesWithoutBackground = StartOffsetAccordingToCover(profile); } catch (Exception ex) { throw new ProcessingException( ex.GetType() + " while detecting number of pages of the cover file: " + profile.AttachmentPage.File + "\r\n" + ex, ErrorCode.Cover_CouldNotOpenFile, ex); } int lastPageWithBackground; try { lastPageWithBackground = nFile - EndOffsetAccordingToAttachment(profile); } catch (Exception ex) { throw new ProcessingException( "Exception while detecting number of pages of the attachment file: " + profile.AttachmentPage.File + "\r\n" + ex, ErrorCode.Attachment_CouldNotOpenFile, ex); } for (var i = 1; i <= nFile; i++) { var backgroundPageNumber = GetBackgroundPageNumber(i, nBackground, profile.BackgroundPage.Repetition, numberOfFrontPagesWithoutBackground, lastPageWithBackground); if (backgroundPageNumber < 1) { continue; } var backgroundPage = stamper.GetImportedPage(backgroundPdfReader, backgroundPageNumber); var backgroundPageSize = backgroundPdfReader.GetPageSize(backgroundPageNumber); var backgroundPageRotation = backgroundPdfReader.GetPageRotation(backgroundPageNumber); var documentPage = stamper.GetUnderContent(i); var documentPageSize = stamper.Reader.GetPageSize(i); if ((stamper.Reader.GetPageRotation(i) == 90) || (stamper.Reader.GetPageRotation(i) == 270)) { //Turn with document page... //* backgroundPageRotation += 90; backgroundPageRotation = backgroundPageRotation % 360; //*/ documentPageSize = new Rectangle(documentPageSize.Height, documentPageSize.Width); } AddPageWithRotationAndScaling(documentPage, documentPageSize, backgroundPage, backgroundPageSize, backgroundPageRotation); } }
private ActionResult AddBackgroundToPdf(string sourceFilename, string destinationFilename, IJob job) { Logger.Trace("Start adding Background to " + sourceFilename); var pdfReader = new PdfReader(sourceFilename); int nFile = pdfReader.NumberOfPages; var backgroundPdfReader = new PdfReader(job.Profile.BackgroundPage.File); Logger.Debug("BackgroundFile: " + Path.GetFullPath(job.Profile.BackgroundPage.File)); int nBackground = backgroundPdfReader.NumberOfPages; int startOffset; //number of front pages without background try { startOffset = StartOffsetAccordingToCover(job.Profile); } catch (Exception ex) { Logger.Error("Excpetion while detecting number of pages of the cover file: " + job.Profile.AttachmentPage.File + "\r\n" + ex); return(new ActionResult(ActionId, 105)); } int endPage; //last page with background try { endPage = nFile - EndOffsetAccordingToAttachment(job.Profile); } catch (Exception ex) { Logger.Error("Excpetion while detecting number of pages of the attachment file: " + job.Profile.AttachmentPage.File + "\r\n" + ex); return(new ActionResult(ActionId, 106)); } var stream = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write); var stamper = new PdfStamper(pdfReader, stream); for (int i = 1; i <= nFile; i++) { int backgroundPage = GetBackgroundPageNumber(i, nBackground, job.Profile.BackgroundPage.Repeat, startOffset, endPage); if (backgroundPage < 1) { continue; } PdfImportedPage page = stamper.GetImportedPage(backgroundPdfReader, backgroundPage); PdfContentByte background = stamper.GetUnderContent(i); Rectangle wmsize = backgroundPdfReader.GetPageSize(backgroundPage); Rectangle pdfsize = pdfReader.GetPageSize(i); if ((pdfReader.GetPageRotation(i) == 90) || (pdfReader.GetPageRotation(i) == 270)) { background.AddTemplate(page, 0, -1f, 1f, 0, ((pdfsize.Height - wmsize.Height) / 2), wmsize.Width + (pdfsize.Width - wmsize.Width) / 2); //270° Logger.Debug("BackgroundPage " + backgroundPage + " turned right, because of automatic rotation of page " + i); } else if ((pdfsize.Height < pdfsize.Width) && (wmsize.Height > wmsize.Width)) { //pdfsize.height and width must be changed for this calculation, because the page was rotated background.AddTemplate(page, 0, -1f, 1f, 0, (pdfsize.Width - wmsize.Height) / 2, wmsize.Width + ((pdfsize.Height - wmsize.Width) / 2)); //270° Logger.Debug("BackgroundPage " + backgroundPage + " turned right to fit better in page " + i); } else { background.AddTemplate(page, (pdfsize.Width - wmsize.Width) / 2, (pdfsize.Height - wmsize.Height) / 2); } //0° } // cos sin -sin cos dx dy //background.AddTemplate(page, 0, 1f, -1f, 0, 0, 0 ); //90° //background.AddTemplate(page, -1f, 0, 0, -1f, 0, 0 ); //180° //background.AddTemplate(page, 0, -1f, 1f, 0, 0, 0 ); //270° //background.AddTemplate(page, 1f, 0, 0, 1f, 0, 0 ); //0° stamper.Close(); return(new ActionResult()); }
public Stream GetPdf() { var document = CreateDefaultDocument(); var tocDocument = CreateDefaultDocument(); var stream = new MemoryStream(); _pdfWriter = PdfWriter.GetInstance(document, stream); _pdfWriter.SetLinearPageMode(); var tocStream = new MemoryStream(); var tocWriter = PdfWriter.GetInstance(tocDocument, tocStream); tocWriter.SetLinearPageMode(); var tocEvent = new PdfEvents(tocDocument, RootDirectory); _pdfWriter.PageEvent = tocEvent; _pdfWriter.StrictImageSequence = true; document.Open(); tocDocument.Open(); AddMetaData(document); AddChapters(document); document.Close(); var fontFooter = PdfFonts.Small; var footer = new Phrase(string.Format("{0}: {1}", Documentation.Project.ProjectNumber, Documentation.Name), fontFooter); var pdfReader = new PdfReader(stream.ToArray()); stream = new MemoryStream(); var stamper = new PdfStamper(pdfReader, stream); var tableOfContents = GenerateTableOfContents(tocEvent, stamper, 0); tocDocument.Add(tableOfContents); tocDocument.Close(); var tocReader = new PdfReader(tocStream.ToArray()); var tocSize = tocReader.NumberOfPages; var toc = new ColumnText(null); var frontPage = new ColumnText(null); var hasFrontPage = Documentation.DocumentationChapters.Any(dc => dc.Chapter is GeneratedChapter && dc.Chapter.Name == "Forside"); tableOfContents = GenerateTableOfContents(tocEvent, stamper, tocSize + (hasFrontPage ? 2 : 0)); toc.AddElement(tableOfContents); var page = stamper.GetImportedPage(pdfReader, 1); int currentPage = 0; while (true) { stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); toc.Canvas = stamper.GetOverContent(currentPage); toc.SetSimpleColumn(60, 72, PageSize.A4.Width - 60, PageSize.A4.Height - 72); if (!ColumnText.HasMoreText(toc.Go())) { break; } } if (hasFrontPage) { frontPage.AddElement(new FrontPageBuilder(Documentation, RootDirectory).GetContent()); page = stamper.GetImportedPage(pdfReader, 1); currentPage = 0; while (true) { stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); frontPage.Canvas = stamper.GetOverContent(currentPage); frontPage.SetSimpleColumn(60, 72, PageSize.A4.Width - 60, PageSize.A4.Height - 72); if (!ColumnText.HasMoreText(frontPage.Go())) { break; } } stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); } int totalPages = pdfReader.NumberOfPages; for (int i = 3; i <= totalPages; ++i) { var canvas = stamper.GetOverContent(i); var table = new PdfPTable(2); var rotation = stamper.Reader.GetPageRotation(i); table.SetWidths(new[] { 10, 1 }); table.TotalWidth = (rotation == 0 ? PageSize.A4.Width : PageSize.A4.Height) - 130; table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.FixedHeight = 20; table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; table.AddCell(footer); table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; table.AddCell(new Phrase(i.ToString(CultureInfo.InvariantCulture), fontFooter)); table.WriteSelectedRows(0, -1, 0, -1, 60, 40, canvas); } stamper.Close(); var outStream = new MemoryStream(stream.ToArray()); return(outStream); }
public string AddBackground(string filename, string printtmp, string busitype, string decltype, string customer) { string tmp_dir = @"d:/ftpserver/declare_tmp_zip/"; string outname = Guid.NewGuid() + ""; DataTable dt_mask = new DataTable(); int top_int = 0, right_int = 0, buttom_int = 0, left_int = 0; string sql = "select POSITIONWEBTOP,POSITIONWEBRIGHT,POSITIONWEBBUTTOM,POSITIONWEBLEFT from config_watermark where CUSTOMER='" + customer + "'"; dt_mask = DBMgr.GetDataTable(sql); if (dt_mask.Rows.Count > 0) { top_int = Convert.ToInt32(dt_mask.Rows[0]["POSITIONWEBTOP"].ToString() == "" ? "0" : dt_mask.Rows[0]["POSITIONWEBTOP"].ToString()); right_int = Convert.ToInt32(dt_mask.Rows[0]["POSITIONWEBRIGHT"].ToString() == "" ? "0" : dt_mask.Rows[0]["POSITIONWEBRIGHT"].ToString()); buttom_int = Convert.ToInt32(dt_mask.Rows[0]["POSITIONWEBBUTTOM"].ToString() == "" ? "0" : dt_mask.Rows[0]["POSITIONWEBBUTTOM"].ToString()); left_int = Convert.ToInt32(dt_mask.Rows[0]["POSITIONWEBLEFT"].ToString() == "" ? "0" : dt_mask.Rows[0]["POSITIONWEBLEFT"].ToString()); } Image img = null; if (busitype == "11" || busitype == "21" || busitype == "31" || busitype == "41" || busitype == "51") { if (printtmp == "海关作业联") { img = Image.GetInstance(Server.MapPath("/FileUpload/进口-海关作业联.png")); } if (printtmp == "企业留存联") { img = Image.GetInstance(Server.MapPath("/FileUpload/进口-企业留存联.png")); } if (printtmp == "海关核销联") { img = Image.GetInstance(Server.MapPath("/FileUpload/进口-海关核销联.png")); } } else { if (printtmp == "海关作业联") { img = Image.GetInstance(Server.MapPath("/FileUpload/出口-海关作业联.png")); } if (printtmp == "企业留存联") { img = Image.GetInstance(Server.MapPath("/FileUpload/出口-企业留存联.png")); } if (printtmp == "海关核销联") { img = Image.GetInstance(Server.MapPath("/FileUpload/出口-海关核销联.png")); } } string destFile = tmp_dir + outname + ".pdf"; FileStream stream = new FileStream(destFile, FileMode.Create, FileAccess.ReadWrite); byte[] pwd = System.Text.Encoding.Default.GetBytes(ConfigurationManager.AppSettings["PdfPwd"]);//密码 PdfReader reader = new PdfReader(filename, pwd); iTextSharp.text.Rectangle psize = reader.GetPageSize(1); var imgWidth = psize.Width + right_int; var imgHeight = psize.Height - top_int + buttom_int; img.ScaleAbsolute(imgWidth, imgHeight); img.SetAbsolutePosition(0 + left_int, 0 - buttom_int); //坐标是从左下角开始算的,注意 PdfStamper stamper = new PdfStamper(reader, stream); //read pdf stream int totalPage = reader.NumberOfPages; for (int current = 1; current <= totalPage; current++) { var canvas = stamper.GetUnderContent(current); var page = stamper.GetImportedPage(reader, current); canvas.AddImage(img); } stamper.Close(); reader.Close(); return(destFile); }
public ActionResult EncuestaPDF(int idencuesta) { //creamos un documento con un guid y lo guardamos en la carpeta temporal de windows string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf"; FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); Document document = new Document(PageSize.A4, 50, 50, 25, 50); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); //creamos el parrafo de titulo de la enciesra EncuestaEntity encuesta = proxy.GetEncuesta(idencuesta); Paragraph titulo = new Paragraph(); titulo.Alignment = Element.ALIGN_CENTER; titulo.Font = FontFactory.GetFont("Arial", 20); titulo.Font.SetStyle(Font.BOLD); titulo.Add(encuesta.TituloEncuesta); document.Add(titulo); //creamos el parrafo de la descripcion Paragraph detalle = new Paragraph(); detalle.Alignment = Element.ALIGN_CENTER; detalle.Font = FontFactory.GetFont("Arial", 17); detalle.Font.SetStyle(Font.BOLD); detalle.Add(encuesta.Descripcion); document.Add(detalle); document.Add(new Paragraph("\n"));//salto de linea //nombre Paragraph nombre = new Paragraph(); nombre.Alignment = Element.ALIGN_LEFT; nombre.Font = FontFactory.GetFont("Arial", 12); nombre.Font.SetStyle(Font.BOLD); nombre.Add("Nombre:______________________________________"); document.Add(nombre); //contrato Paragraph contrato = new Paragraph(); contrato.Alignment = Element.ALIGN_LEFT; contrato.Font = FontFactory.GetFont("Arial", 12); contrato.Font.SetStyle(Font.BOLD); contrato.Add("Contrato:______________________ Fecha:_______________________"); document.Add(contrato); //Separador Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.LIGHT_GRAY, Element.ALIGN_LEFT, 1))); document.Add(p); document.Add(new Paragraph("\n")); //listamos las preguntas y las respuestas y las agregamos a un parrafo List <RelPreguntaEncuestasEntity> lista_de_relaciones = rel_preg_encuesta.GetRelPreguntaEncuestasList().Where(x => x.IdEncuesta == encuesta.IdEncuesta).ToList(); foreach (var a in lista_de_relaciones) { Paragraph pregunta = new Paragraph(); pregunta.Alignment = Element.ALIGN_LEFT; pregunta.Font = FontFactory.GetFont("Arial", 11); pregunta.Font.SetStyle(Font.BOLD); pregunta.Add(a.Pregunta.Pregunta); document.Add(pregunta); Paragraph respuesta = new Paragraph(); respuesta.Alignment = Element.ALIGN_LEFT; respuesta.Font = FontFactory.GetFont("Arial", 10); if (a.Pregunta.IdTipoPregunta == 1) { respuesta.Add("_________________________________________________________________________________________"); respuesta.Add("\n"); respuesta.Add("_________________________________________________________________________________________"); respuesta.Add("\n"); respuesta.Add("_________________________________________________________________________________________"); } else if (a.Pregunta.IdTipoPregunta == 2) { respuesta.Add("Si( ) No( )"); } else { List <RelPreguntaOpcMultsEntity> relaciones = relpregunta_resp.GetRelPreguntaOpcMultsList().Where(x => x.IdPregunta == a.IdPregunta).ToList(); foreach (var resp in relaciones) { ResOpcMultsEntity respuestas = Respuestas.GetResOpcMultsList().Where(o => o.Id_ResOpcMult == resp.Id_ResOpcMult).Select(o => o).First(); respuesta.Add("( )" + respuestas.ResOpcMult); respuesta.Add("\n"); } } document.Add(respuesta); document.Add(new Paragraph("\n")); } document.Close(); //cerramos el documento y lo volvemos a abrir para agregar el numero de pagina a cada hoja PdfReader rd = new PdfReader(fileName); string fileName2 = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf"; PdfStamper ps = new PdfStamper(rd, new FileStream(fileName2, FileMode.Create)); PdfImportedPage page; for (int i = 1; i <= rd.NumberOfPages; i++) { PdfContentByte canvas = ps.GetOverContent(i); page = ps.GetImportedPage(rd, i); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); canvas.BeginText(); canvas.SetFontAndSize(bf, 8); canvas.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " " + i, 300.7f, 20.7f, 0); canvas.EndText(); canvas.AddTemplate(page, 0, 0); } ps.Close(); //retornamos el archivo pero ahora con el nombre del titulo de la encuesta return(File(fileName2, "application/pdf", encuesta.TituloEncuesta + ".pdf")); }
public static string CreatePDF2(DatosComprobante dt, Comprobante comprobante, string rutaPDF, string nombrePDF) { //*** Copia el recurso embebido en un directorio temporal , cuando se le envíe la plantilla del pdf en la dll // ContentLoading.GetPDFEmbedded(); //*** Esto hay que activar cuando el pdf esté compilado en la librería try { var boldTableFont = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.BOLD); var bodyFont = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL); //*** Configuración de directorios para los diferentes formatos string carpetaPrincipal = Properties.Settings.Default.PathDefecto; string carpetaFormatosFacturas = Properties.Settings.Default.DeFacturas; string formatoPDFCabecera = Properties.Settings.Default.EsteFormatoFacturaCabecera; string formatoPDFDetalles = Properties.Settings.Default.EsteFormatoFacturaDetalles; string formatoPDFTotales = Properties.Settings.Default.EsteFormatoFacturaTotales; string carpetaGeneradasFacturas = Properties.Settings.Default.FacturasGeneradas; string rutaCompleta = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFCabecera; string rutaCompleta_1 = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFDetalles; string rutaCompleta_2 = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFTotales; string nombreFacturaGenerada = Properties.Settings.Default.ArchivoTemporal; string nuevaFacturaCompleta = carpetaPrincipal + carpetaGeneradasFacturas + @"\" + nombreFacturaGenerada; // estos dos archivos, se eliminan al terminar el proceso string detalletemporal = carpetaPrincipal + carpetaGeneradasFacturas + @"\detalle_temporal.pdf"; string totalestemporal = carpetaPrincipal + carpetaGeneradasFacturas + @"\totales_temporal.pdf"; //*** Esto se activa cuando el pdf está dentro de la librería //string fileNameExisting = ContentLoading.CrearCarpetaTemporal("modelo_facturaFinal.pdf"); //*** Va junto con la opción de arriba string fileNameExisting = rutaCompleta; string fileNameExisting_1 = rutaCompleta_1; string fileNameExisting_2 = rutaCompleta_2; //*** Archivo resultante temporal string fileNameNew = nuevaFacturaCompleta; //*** estos dos archivos, se eliminan al terminar el proceso string fileNameNew_1 = detalletemporal; string fileNameNew_2 = totalestemporal; //*** Proceso de estampado de la cabecera del documento using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open)) using (var newFileStream = new FileStream(fileNameNew, FileMode.Create)) { // Open existing PDF PdfReader pdfReader = new PdfReader(existingFileStream); Rectangle pagesize = pdfReader.GetPageSize(1); // PdfStamper, which will create PdfStamper stamper = new PdfStamper(pdfReader, newFileStream); var form = stamper.AcroFields; //var fieldKeys = form.Fields.Keys; var imagepath = comprobante.archivo; using (FileStream fs = new FileStream(imagepath, FileMode.Open)) { var png = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), System.Drawing.Imaging.ImageFormat.Png); png.Alignment = iTextSharp.text.Image.ALIGN_RIGHT; png.SetAbsolutePosition(41, 1010); png.ScaleAbsoluteHeight(100); png.ScaleAbsoluteWidth(365); PdfContentByte over = null; over = stamper.GetOverContent(1); // 1 = página over.AddImage(png); } //*** mapeo de datos de la factura ESTAMPADO DE LOS DATOS EN LA PLANTILLA //*** TECNOLOGÍA ACROFIELDS form.SetField("RUC", dt.Ruc); form.SetField("NROFACTURA", comprobante.codDoc); form.SetField("NROAUTORIZACION", dt.numeroAutorizacion); form.SetField("AMBIENTE", dt.ambiente); form.SetField("EMISION", dt.estado); form.SetField("CLAVEACCESONUMEROS", dt.numeroAutorizacion); //***mapeo de datos de la empresa form.SetField("NOMBREEMPRESA", "ComputerEC"); form.SetField("DIRECCION1EMPRESA", "Calle Homero Salas OE5-148 y Altar"); form.SetField("DIRECCION2EMPRESA", "Sector del Antiguo Aeropuerto"); form.SetField("DESCRIPCION1EMPRESA", "Teléfonos: 0983833901 0991324900"); form.SetField("DESCRIPCION2EMPRESA", "Horarios: Lun-Vie 08:00 a 18:00"); //***mapeo de los datos del cliente //***ESTOS DATOS //form.SetField("RazonSocial", comprobante.Comprobante.razonSocial); //form.SetField("FechaEmision", comprobante.Comprobante.fechaEmision); //form.SetField("Identificacion", comprobante.Comprobante.ruc); #region Detalles PdfPTable itemTable = new PdfPTable(9); itemTable.HorizontalAlignment = 0; itemTable.WidthPercentage = 146; itemTable.SpacingBefore = 10f; itemTable.SpacingAfter = 10f; itemTable.SetWidths(new float[] { 3f, /*3f,*/ 2f, 6f, 4f, 4f, 4f, 3f, 3f, 3f }); // then set the column's __relative__ widths itemTable.DefaultCell.Border = Rectangle.BOX; // VALIDACION DE LOS CAMPOS QUE SE GENERAN EN EL PDF PdfPCell cell1 = new PdfPCell(new Phrase(new Chunk("Cod.Principal", boldTableFont))); cell1.HorizontalAlignment = 1; itemTable.AddCell(cell1); //PdfPCell cell2 = new PdfPCell(new Phrase(new Chunk("Cod.Auxiliar", boldTableFont))); //cell2.HorizontalAlignment = 1; //itemTable.AddCell(cell2); PdfPCell cell3 = new PdfPCell(new Phrase(new Chunk("Cantidad", boldTableFont))); cell3.HorizontalAlignment = 1; itemTable.AddCell(cell3); PdfPCell cell4 = new PdfPCell(new Phrase(new Chunk("Descripcion", boldTableFont))); cell4.HorizontalAlignment = 1; itemTable.AddCell(cell4); PdfPCell cell5 = new PdfPCell(new Phrase(new Chunk("Det.Adicional1", boldTableFont))); cell5.HorizontalAlignment = 1; itemTable.AddCell(cell5); PdfPCell cell6 = new PdfPCell(new Phrase(new Chunk("Det.Adicional2", boldTableFont))); cell6.HorizontalAlignment = 1; itemTable.AddCell(cell6); PdfPCell cell7 = new PdfPCell(new Phrase(new Chunk("Det.Adicional3", boldTableFont))); cell7.HorizontalAlignment = 1; itemTable.AddCell(cell7); PdfPCell cell8 = new PdfPCell(new Phrase(new Chunk("ValorUnit", boldTableFont))); cell8.HorizontalAlignment = 1; itemTable.AddCell(cell8); PdfPCell cell9 = new PdfPCell(new Phrase(new Chunk("Descuento", boldTableFont))); cell9.HorizontalAlignment = 1; itemTable.AddCell(cell9); PdfPCell cell10 = new PdfPCell(new Phrase(new Chunk("PrecioTotal", boldTableFont))); cell10.HorizontalAlignment = 1; itemTable.AddCell(cell10); itemTable.HeaderRows = 1; foreach (DetalleComprobante fila in comprobante.detalles) { itemTable.AddCell(fila.codigoPrincipal.ToString()); //itemTable.AddCell(fila.codigoAuxiliar.ToString()); itemTable.AddCell(fila.cantidad.ToString()); itemTable.AddCell(fila.descripcion.ToString()); itemTable.AddCell(fila.detalleadicional1.ToString()); itemTable.AddCell(fila.detalleadicional2.ToString()); itemTable.AddCell(fila.detalleadicional3.ToString()); itemTable.AddCell(fila.precioUnitario.ToString()); itemTable.AddCell(fila.descuento.ToString()); itemTable.AddCell(fila.totalSinImpueto.ToString()); } ColumnText column = new ColumnText(stamper.GetOverContent(1)); Rectangle rectPage1 = new Rectangle(43, 36, 559, 856); // POSICIÓN DONDE INICIA LA TABLA column.SetSimpleColumn(rectPage1); column.AddElement(itemTable); int pagecount = 1; Rectangle rectPage2 = new Rectangle(43, 36, 559, 1000); // 1000 = POSICIÓN DEL TITULO DE LA TABLA EN CADA PÁGINA int status = column.Go(); while (ColumnText.HasMoreText(status)) { status = triggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount); } #endregion itemTable.SpacingBefore = 20; altotal = itemTable.TotalHeight; stamper.FormFlattening = true; //stamper.FreeTextFlattening = true; stamper.Close(); pdfReader.Close(); } //*** Proceso de estampado de los totales del documento en otro PDF using (var existingFileStream = new FileStream(fileNameExisting_2, FileMode.Open)) using (var newFileStream = new FileStream(fileNameNew_2, FileMode.Create)) { // Open existing PDF PdfReader pdfReader = new PdfReader(existingFileStream); // PdfStamper, which will create PdfStamper stamper = new PdfStamper(pdfReader, newFileStream); var form = stamper.AcroFields; var fieldKeys = form.Fields.Keys; //*** mapeo de datos de la factura form.SetField("SUBTOTAL12", comprobante.totalConImpuestos.ToString()); form.SetField("SUBTOTALCERO", ""); form.SetField("SUBTOTALNOIVA", ""); form.SetField("SUBTOTALEXCENTO", ""); form.SetField("SUBTOTALSINIMPUESTOS", comprobante.totalSinImpuetos.ToString()); form.SetField("TOTALDESCUENTO", comprobante.totalDescuento.ToString()); form.SetField("ICE", ""); form.SetField("VALORIVA", ""); form.SetField("IRBPNR", ""); form.SetField("PROPINA", comprobante.propina.ToString()); form.SetField("VALORTOTAL", comprobante.importeTotal.ToString()); stamper.FormFlattening = true; //stamper.FreeTextFlattening = true; stamper.Close(); pdfReader.Close(); } // SE ACTIVA CUANDO SE REQUIERA HACER EL PROCESO EN MEMORIA //List<byte[]> fbytes = new List<byte[]>(); //MemoryStream ms = GenerarRIDE.CreatePDF1Stream(fileNameNew); //ms.Position = 0; //fbytes.Add(ms.ToArray()); //ms = GenerarRIDE.CreatePDF1Stream(fileNameNew_1); //ms.Position = 0; //fbytes.Add(ms.ToArray()); //ms = GenerarRIDE.CreatePDF1Stream(fileNameNew_2); //ms.Position = 0; //fbytes.Add(ms.ToArray()); //MemoryStream PDFData = new MemoryStream(); ////*** Se guarda el archivo generado ////string fileNameNew = nuevaFacturaCompleta; //PDFData = new MemoryStream(concatAndAddContent(fbytes)); // une los 3 archivos //PDFData.Position = 0; ////MemoryStream ms1 = GenerarRIDE.CreatePDF1Stream(final3); ////ms1.Position = 0; //SavePDFFile(final3, PDFData); // Merge de archivos #region MergePDF //altotal 856 float y = -altotal - 250; // obteniendo las rutas string src = rutaPDF + "archivotemporal.pdf"; string src1 = rutaPDF + "totales_temporal.pdf"; string final = rutaPDF + nombrePDF; PdfReader reader = new PdfReader(src); PdfStamper stamper1 = new PdfStamper(reader, new FileStream(final, FileMode.Create)); PdfContentByte canvas = stamper1.GetUnderContent(1); PdfReader r; PdfImportedPage page; PdfReader s_reader = new PdfReader(src1); Rectangle pageSize = reader.GetPageSize(1); int n = reader.NumberOfPages; for (int i = 1; i <= n; i++) { r = new PdfReader(src1); page = stamper1.GetImportedPage(r, 1); canvas.AddTemplate(page, 0, y); //float x float y stamper1.Writer.FreeReader(r); r.Close(); } stamper1.Close(); s_reader.Close(); reader.Close(); return("True"); #endregion } catch (Exception e0) { return("No se generó el PDF : " + e0.Message); } }