예제 #1
8
        private void button1_Click(object sender, EventArgs e)
        {
            var datecombination = listBox1.SelectedValue.ToString();

            datecombination = datecombination.Replace("To", ",");
            var           arrayelement = datecombination.Split(',');
            List <string> queryList    = Utilities.DataBaseUtility.GetList("select distinct start_date,end_date from Timesheets");
            //var stringvalue = String.Format("select e.FirstName,e.LastName,e.Role,g.gross_amt,n.netpay_amt,n.deduction_amt from ((employees e join netpay n on e.DocNum=n.Emp_id) join grosspay g on e.docnum=g.emp_id) where e.docNum=104 and n.paystartdate='{0}' and n.payenddate='{1}'", arrayelement[0].Substring(0, arrayelement[0].Length - 15).Trim(), arrayelement[1].Substring(0, arrayelement[0].Length - 14).Trim());
            int employeeID = 0;

            try
            {
                employeeID = Convert.ToInt32(employeesAdmin.Text);
            }
            catch (Exception ex)
            {
                employeeID = 104;
            }

            if (employeeID < 111 && employeeID > 100)
            {
            }
            else
            {
                employeeID = 104;
            }


            //var stringvalue = "SELECT e.FirstName,e.LastName,e.Role,n.netpay_amt,n.deduction_amt from employees e inner join netpay n on e.DocNum=n.Emp_id";
            var stringvalue = "SELECT * FROM ([employees] AS [e] INNER JOIN [grosspay] AS [g] ON [e].[DocNum] = [g].[emp_id]) INNER JOIN [NETPAY] AS [N] ON [N].[emp_id]=[e].[DocNum] where [e].docNum=" + employeeID;
            //var stringvalue = String.Format("SELECT EMPLOYEES.FirstName, EMPLOYEES.Role, EMPLOYEES.gross_amt, EMPLOYEES.Role, NetPay.NetPay_Amt, NetPay.Benefits_Amt, NetPay.Deductions_Amt, GrossPay.GrossPay, GrossPay.PayStartDate, GrossPay.PayEndDateFROM EMPLOYEES, NetPay, GrossPay;");
            var value = Utilities.DataBaseUtility.GetList(stringvalue);

            String[] finalValue = value[1].Split(',');

            if (button1.Text.Equals("Download PaySlip"))
            {
                String     path     = System.AppDomain.CurrentDomain.BaseDirectory;
                String     fileName = "payslip.pdf";
                FileStream fs       = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                iTextSharp.text.Document      doc    = new iTextSharp.text.Document();
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs);
                doc.Open();
                String spacing   = "                                                                                         ";
                String imagepath = Directory.GetCurrentDirectory();

                imagepath = imagepath.Replace("\\bin\\Debug", "\\Images\\HawkLogo.bmp");
                //  + "\\Images\\HawkLogo.bmp";
                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath);



                doc.Add(new Paragraph("-------------------------------------PAYSLIP - METRO VIDEO PHOTO -------------------------------------              "));
                doc.Add(gif);
                doc.Add(new Paragraph(spacing + "Employee ID : " + finalValue[0]));
                doc.Add(new Paragraph(spacing + "First Name : " + finalValue[2]));
                doc.Add(new Paragraph(spacing + "Last Name : " + finalValue[3]));
                doc.Add(new Paragraph(spacing + "Email ID : " + finalValue[12]));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph("Pay Period:"));
                doc.Add(new Paragraph("Start Date : " + finalValue[23]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("End Date : " + finalValue[24]));
                doc.Add(new Paragraph("---------------------------"));
                doc.Add(new Paragraph("Total Overtime Pay : " + finalValue[25]));
                doc.Add(new Paragraph("---------------------------------------------"));
                doc.Add(new Paragraph("Gross Pay : " + finalValue[26]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Benefit Amount : " + finalValue[31]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Deduction Amount : " + finalValue[32]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Final Pay (Net Pay) : " + finalValue[36]));



                doc.Close();
                string FileLocation = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
                //string WatermarkLocation = "C:\\Users\\Prithiviraj\\Desktop\\PDF Document\\Myimage.png";
                String WatermarkLocation = Directory.GetCurrentDirectory();

                WatermarkLocation = WatermarkLocation.Replace("\\bin\\Debug", "\\Images\\bgconfidential.png");

                Document document = new Document();
                iTextSharp.text.pdf.PdfReader  pdfReader = new iTextSharp.text.pdf.PdfReader(FileLocation);
                iTextSharp.text.pdf.PdfStamper stamp     = new iTextSharp.text.pdf.PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "_" + finalValue[0] + ".pdf"), FileMode.Create));

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
                img.SetAbsolutePosition(0, 5); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)

                iTextSharp.text.pdf.PdfContentByte waterMark;
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    waterMark = stamp.GetUnderContent(page);
                    waterMark.AddImage(img);
                }
                stamp.FormFlattening = true;
                stamp.Close();
                label1.Visible = true;
                label1.Text    = "Your file (payslip.pdf) is succssfully downloaded";
            }

            else if (button1.Text.Equals("View Gross Pay"))
            {
                label1.Visible = true;
                label1.Text    = "Gross Pay";

                heading1.Visible = true;
                heading2.Visible = true;
                heading3.Visible = true;
                heading4.Visible = true;
                heading5.Visible = true;
                heading6.Visible = true;

                value1.Visible = true;
                value2.Visible = true;
                value3.Visible = true;
                value4.Visible = true;
                value5.Visible = true;
                value6.Visible = true;


                heading1.Text = "Employee ID: ";
                heading2.Text = "Regular Hourly Pay Rate: ";
                heading3.Text = "Overtime Hourly Pay Rate: ";
                heading4.Text = "Num of Regular Hours: ";
                heading5.Text = "Num of overtime Hours: ";
                heading6.Text = "Gross Pay: ";

                int regHours      = Convert.ToInt32(finalValue[22]) / Convert.ToInt32(finalValue[20]);
                int overTimeHours = Convert.ToInt32(finalValue[25]) / Convert.ToInt32(finalValue[21]);

                value1.Text = finalValue[0];
                value2.Text = "$" + finalValue[20];
                value3.Text = "$" + finalValue[21];
                value4.Text = regHours.ToString();
                value5.Text = overTimeHours.ToString();
                value6.Text = "$" + finalValue[26];
            }
            else if (button1.Text.Equals("View Net Pay"))
            {
                label1.Visible = true;
                label1.Text    = "Net Pay";

                heading1.Visible = true;
                heading2.Visible = true;
                heading3.Visible = true;
                heading4.Visible = true;
                heading5.Visible = true;
                //  heading6.Visible = true;

                value1.Visible = true;
                value2.Visible = true;
                value3.Visible = true;
                value4.Visible = true;
                value5.Visible = true;
                //   value6.Visible = true;


                heading1.Text = "Employee ID: ";
                heading2.Text = "Gross Pay: ";
                heading3.Text = "Total Benefits: ";
                heading4.Text = "Total Deductions: ";
                heading5.Text = "Net Pay: ";
                //  heading6.Text = "Gross Pay: ";

                value1.Text = finalValue[0];
                value2.Text = "$" + finalValue[26];
                value3.Text = "$" + finalValue[31];
                value4.Text = "$" + finalValue[32];
                value5.Text = "$" + finalValue[36];
                // value6.Text = finalValue[26];
            }
        }
예제 #2
4
        /// <summary>
        /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
        /// </summary>
        public static PdfDocument Open(MemoryStream sourceStream, PdfDocumentOpenMode openmode)
        {
            PdfDocument outDoc = null;
            sourceStream.Position = 0;

            try
            {
                outDoc = PdfReader.Open(sourceStream, openmode);
            }
            catch (PdfSharp.Pdf.IO.PdfReaderException)
            {
                //workaround if pdfsharp doesn't support this pdf
                sourceStream.Position = 0;
                MemoryStream outputStream = new MemoryStream();
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourceStream);
                iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream);
                pdfStamper.FormFlattening = true;
                pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
                pdfStamper.Writer.CloseStream = false;
                pdfStamper.Close();

                outDoc = PdfReader.Open(outputStream, openmode);
            }

            return outDoc;
        }
        public byte[] PrintSignToPDF_MemoriaAllPages_TextSharp(Stream File, String Firma, String Firmante)
        {
            MemoryStream outputPdfStream = new MemoryStream();
            PdfDocument document = PdfDocument.FromStream(File);
            document.SerialNumber = "s/va4uPX-1f/a0cHS-wcqFnYOT-gpOHk4qL-h5OAgp2C-gZ2KioqK";
            PdfFont pdfFont = document.CreateStandardFont(PdfStandardFont.Helvetica);
            byte[] pdfBuffer = document.WriteToMemory();
            var reader = new iTextSharp.text.pdf.PdfReader(pdfBuffer);
            var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

            iTextSharp.text.pdf.PdfContentByte pdfContentByte2;
            iTextSharp.text.Rectangle pageSize;
            int NumOfPages = document.Pages.Count;

            for (int j = 1; j <= NumOfPages; j++)
            {

                pdfContentByte2 = stamper.GetOverContent(j);
                pageSize = reader.GetPageSizeWithRotation(j);
                pdfContentByte2.BeginText();

                //Firma = String.Format("{0} {1}", Firma, Firmante);
                string[] arrays = Firma.Split(' ');

                //iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, Encoding.ASCII.EncodingName, true, true);
                iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont("c:/windows/fonts/arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, true, true);

                pdfContentByte2.SetFontAndSize(baseFont, 8);
                //pdfContentByte2.SetRGBColorFill(192, 192, 192);
                pdfContentByte2.SetRGBColorFill(0, 0, 0);

                StringBuilder bloqueFirma = new StringBuilder();
                int contador = 0;
                int saltoLineaPixeles = 0;
                for (int i = 0; i < arrays.Length; i++)
                {
                    bloqueFirma.Append(arrays[i]);
                    bloqueFirma.Append(" ");
                    contador++;
                    if ((contador == 35) || ((saltoLineaPixeles > 13) && (contador == 36)))
                    {
                        pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                             pageSize.Width - (pageSize.Width / 2) - 100,
                                                            (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);
                        contador = 0;
                        bloqueFirma = new StringBuilder();
                        saltoLineaPixeles = saltoLineaPixeles + 10;
                    }
                    else if ((i + 1) == arrays.Length)
                    {
                        pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                             pageSize.Width - (pageSize.Width / 2) - 100,
                                                            (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);
                        saltoLineaPixeles = saltoLineaPixeles + 10;
                    }
                }

                String[] datos = Firmante.Split('[');
                String Firmante_ = datos[0];
                String pagina = datos[1];
                //Firmante_ = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(Firmante_)));

                pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, Firmante_.ToString(),
                                                    pageSize.Width - (pageSize.Width / 2) - 100,
                                                (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);

                saltoLineaPixeles = saltoLineaPixeles + 10;
                pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, pagina.ToString(),
                                                    pageSize.Width - (pageSize.Width / 2) - 100,
                                                (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);

                pdfContentByte2.EndText();
            }

            stamper.Close();

            outputPdfStream.Close();
            outputPdfStream.Dispose();
            document.Close();

            return outputPdfStream.GetBuffer();
        }
예제 #4
0
        public static void SignPdfFile(string sourceDocument, string destinationPath, Stream privateKeyStream, string password, string reason, string location)
        {
            Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, password.ToCharArray());

            privateKeyStream.Dispose();
            string alias = null;

            foreach (string tAlias in pk12.Aliases)
            {
                if (pk12.IsKeyEntry(tAlias))
                {
                    alias = tAlias;
                    break;
                }
            }
            var pk = pk12.GetKey(alias).Key;

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourceDocument);
            using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite)) {
                using (iTextSharp.text.pdf.PdfStamper stamper = iTextSharp.text.pdf.PdfStamper.CreateSignature(reader, fout, '\0')) {
                    iTextSharp.text.pdf.PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                    iTextSharp.text.pdf.BaseFont bf   = iTextSharp.text.pdf.BaseFont.CreateFont(System.Web.HttpContext.Current.Server.MapPath("~/fonts/iconic/fonts/Material-Design-Iconic-Font.ttf"), iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    iTextSharp.text.Font         font = new iTextSharp.text.Font(bf, 11);
                    appearance.Layer2Font = font;
                    //appearance.Image = new iTextSharp.text.pdf.PdfImage();
                    appearance.Reason   = reason;
                    appearance.Location = location;
                    appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), 1, "Icsi-Vendor");
                    iTextSharp.text.pdf.security.IExternalSignature es = new iTextSharp.text.pdf.security.PrivateKeySignature(pk, "SHA-256");
                    iTextSharp.text.pdf.security.MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, iTextSharp.text.pdf.security.CryptoStandard.CMS);
                    stamper.Close();
                }
            }
        }
예제 #5
0
        /// <summary>
        /// 利用itextsharp生成文字签名
        /// </summary>
        public void ConvertPdf2()
        {
            string sourcePath = $"C:\\test\\source.pdf";
            string targetPath = $"E:\\test\\target.pdf";
            string fontPath   = $"C:\\Windows\\Fonts\\simkai.ttf";

            //读原始PDF
            using (iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourcePath))
            {
                //定义流
                using (iTextSharp.text.pdf.PdfStamper stream = new iTextSharp.text.pdf.PdfStamper(reader, new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None)))
                {
                    //加载字体
                    iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.pdf.BaseFont.CreateFont(fontPath, iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED), 12);

                    //获取顶层图层
                    iTextSharp.text.pdf.PdfContentByte canvas = stream.GetOverContent(1);

                    iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名1", font), 3090, 93, 0);   //left, bottom, rotation
                    iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名2", font), 3090, 73, 0);   //left, bottom, rotation
                    iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名3", font), 3090, 53, 0);   //left, bottom, rotation
                    iTextSharp.text.pdf.ColumnText.ShowTextAligned(canvas, iTextSharp.text.Element.ALIGN_LEFT, new iTextSharp.text.Phrase("签名4", font), 3090, 33, 0);   //left, bottom, rotation
                }
            }
        }
예제 #6
0
        private void PDFSharpConvert(string pdfFileName)
        {
            FileStream stream = File.OpenRead(pdfFileName);

            byte[] fileArray = new byte[stream.Length];
            stream.Read(fileArray, 0, fileArray.Length);
            MemoryStream sourceStream = new MemoryStream(fileArray);

            stream.Close();
            stream.Dispose();
            MemoryStream outputStream = null;

            sourceStream.Position = 0;
            outputStream          = new MemoryStream();
            iTextSharp.text.pdf.PdfReader  reader     = new iTextSharp.text.pdf.PdfReader(sourceStream);
            iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream);
            pdfStamper.FormFlattening = true;
            pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_7);
            pdfStamper.Writer.CloseStream = false;
            pdfStamper.Close();
            using (FileStream file = new FileStream(pdfFileName, FileMode.Create, FileAccess.Write))
            {
                outputStream.WriteTo(file);
            }
        }
예제 #7
0
        public static bool CropCockleBriefPages(string src)
        {
            // works for both saddle stitch and perfect bind
            string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "brief cropped.pdf");

            try
            {
                using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create))
                {
                    iTextSharp.text.pdf.PdfRectangle croppedRectangle = new iTextSharp.text.pdf.PdfRectangle(377f, 189f, 0f, 792f);
                    iTextSharp.text.pdf.PdfReader    reader           = new iTextSharp.text.pdf.PdfReader(src);

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i);
                        pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangle);
                    }

                    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);
                    stamper.Close();
                    reader.Close();
                }
                System.IO.File.Delete(src);
                System.IO.File.Move(dest, src);
                return(true);
            }
            catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); }
        }
예제 #8
0
        /// <summary>
        /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
        /// </summary>
        public static PdfDocument Open(MemoryStream sourceStream, PdfDocumentOpenMode openmode)
        {
            PdfDocument outDoc = null;

            sourceStream.Position = 0;

            try
            {
                outDoc = PdfReader.Open(sourceStream, openmode);
            }
            catch (PdfSharp.Pdf.IO.PdfReaderException)
            {
                // workaround if pdfsharp doesn't support this pdf
                sourceStream.Position = 0;
                MemoryStream outputStream                 = new MemoryStream();
                iTextSharp.text.pdf.PdfReader  reader     = new iTextSharp.text.pdf.PdfReader(sourceStream);
                iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream);
                pdfStamper.FormFlattening = true;
                pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
                pdfStamper.Writer.CloseStream = false;
                pdfStamper.Close();

                outDoc = PdfReader.Open(outputStream, openmode);
            }

            return(outDoc);
        }
        private System.IO.MemoryStream addBlankPages(System.IO.MemoryStream orig_stream, int num_to_add = 1)
        {
            if (num_to_add == 0)
            {
                return(orig_stream);
            }

            System.IO.MemoryStream dest_stream = null;
            try
            {
                dest_stream = new System.IO.MemoryStream();


                var reader  = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray());
                var stamper = new iTextSharp.text.pdf.PdfStamper(reader, dest_stream);
                for (var i = 1; i <= num_to_add; i++)
                {
                    stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1));
                }
                stamper.Close();
                reader.Close();
            }
            catch (Exception excpt)
            {
                System.Diagnostics.Debug.WriteLine(excpt);
            }
            return(dest_stream);
        }
예제 #10
0
        // ====================================================================================================


        // ====================================================================================================
        #region MÉTODOS PÚBLICOS RECLAMACIONES
        // ====================================================================================================

        public void GenerarReclamación(Centros centro, Conductor conductor, DateTime fecha, string ruta)
        {
            // Creamos el lector del documento.
            string rutaPlantilla = Utils.CombinarCarpetas(App.RutaInicial, $"/Plantillas/Reclamacion.pdf");

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(rutaPlantilla);
            // Creamos el 'modificador' del documento.
            FileStream fs = new FileStream(ruta, FileMode.Create);

            iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, fs);

            // Extraemos los campos del documento.
            iTextSharp.text.pdf.AcroFields campos = stamper.AcroFields;

            // Asignamos los campos
            campos.SetField("Centro", centro.ToString().ToUpper());
            campos.SetField("Trabajador", $"{conductor.Apellidos}, {conductor.Nombre} ({conductor.Id:000})");
            campos.SetField("FechaCabecera", $"{fecha:MMMM - yyyy}".ToUpper());
            campos.SetField("NumeroReclamacion", $"Nº Reclamación: {fecha:yyyyMM}{conductor.Id:000}/01");
            campos.SetField("FechaFirma", $"{DateTime.Today:dd - MM - yyyy}");

            // Cerramos los elementos abiertos
            stamper.Close();
            fs.Close();
            reader.Close();
        }
예제 #11
0
        public static bool CropCoverAndInsideCover(string src, int?coverLength)
        {
            // works for both saddle stitch and perfect bind
            string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "cover cropped.pdf");

            try
            {
                using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create))
                {
                    iTextSharp.text.pdf.PdfRectangle croppedRectangleCover;
                    switch (coverLength)
                    {
                    case 48:
                    default:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 130f, 21f, 741f);
                        break;

                    case 49:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 120f, 21f, 741f);
                        break;

                    case 50:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 108f, 21f, 741f);
                        break;

                    case 51:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 92f, 21f, 741f);
                        break;
                    }
                    iTextSharp.text.pdf.PdfRectangle croppedRectangleInsideCover = new iTextSharp.text.pdf.PdfRectangle(377f, 189f, 0f, 792f);

                    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src);

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i);
                        if (i == 1)
                        {
                            pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangleCover);
                        }
                        else
                        {
                            pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangleInsideCover);
                        }
                    }

                    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);
                    stamper.Close();
                    reader.Close();
                }
                System.IO.File.Delete(src);
                System.IO.File.Move(dest, src);
                return(true);
            }
            catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); }
        }
예제 #12
0
        public static void FillTemplate(string path, Stream outputStream, Dictionary<string, string> fields)
        {
            var pdfReader = new iTextSharp.text.pdf.PdfReader(path);
            var pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, outputStream);
            var pdfFormFields = pdfStamper.AcroFields;

            foreach (var field in fields)
            {
                pdfFormFields.SetField(field.Key, field.Value);
            }

            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
        }
예제 #13
0
        private void SaveImages(string InputPDFFile, int specificPageNumber, int degree)
        {
            Directory.CreateDirectory(Constents.ROOTPATH + "\\" + Constents.PDFROTATE_FOLDER);
            var    filename = Path.GetFileName(InputPDFFile);
            string outfile  = Constents.ROOTPATH + "\\" + Constents.PDFROTATE_FOLDER + filename;

            txtOutputPath.Text = outfile;

            using (FileStream outStream = new FileStream(outfile, FileMode.Create))
            {
                iTextSharp.text.pdf.PdfReader  reader  = new iTextSharp.text.pdf.PdfReader(InputPDFFile);
                iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, outStream);
                int noofPages = reader.NumberOfPages;

                if (specificPageNumber > 0) //Rotae Specific Page
                {
                    iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(specificPageNumber);
                    int desiredRot = degree; // 90 degrees clockwise from what it is now
                    iTextSharp.text.pdf.PdfNumber rotation = pageDict.GetAsNumber(iTextSharp.text.pdf.PdfName.ROTATE);

                    if (rotation != null)
                    {
                        desiredRot += rotation.IntValue;
                        desiredRot %= 360; // must be 0, 90, 180, or 270
                    }
                    pageDict.Put(iTextSharp.text.pdf.PdfName.ROTATE, new iTextSharp.text.pdf.PdfNumber(desiredRot));
                }
                else // Rotate All Pages
                {
                    for (int i = 1; i <= noofPages; i++)
                    {
                        iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i);
                        int desiredRot = degree; // 90 degrees clockwise from what it is now
                        iTextSharp.text.pdf.PdfNumber rotation = pageDict.GetAsNumber(iTextSharp.text.pdf.PdfName.ROTATE);

                        if (rotation != null)
                        {
                            desiredRot += rotation.IntValue;
                            desiredRot %= 360; // must be 0, 90, 180, or 270
                        }
                        pageDict.Put(iTextSharp.text.pdf.PdfName.ROTATE, new iTextSharp.text.pdf.PdfNumber(desiredRot));
                    }
                }

                stamper.Close();
            }
        }
예제 #14
0
        public virtual void manipulatePdf(string src, string dest)
        {
            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(dest, System.IO.FileMode.Create, System.IO.FileAccess.Write));

            stamper.RotateContents = false;
            Phrase header = new Phrase("Copy", new Font(Font.FontFamily.HELVETICA, 14));

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                float x = reader.GetPageSize(i).Width / 2;
                float y = reader.GetPageSize(i).GetTop(20);
                ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, header, x, y, 0);
            }
            stamper.Close();
            reader.Close();
        }
        private System.IO.MemoryStream cropTypesetCover(System.IO.MemoryStream orig_stream)
        {
            {
                // works for both saddle stitch and perfect bind
                System.IO.MemoryStream dest_stream = null;
                try
                {
                    dest_stream = new System.IO.MemoryStream();
                    iTextSharp.text.pdf.PdfRectangle croppedRectangleCover;
                    switch (LengthOfCover)
                    {
                    case 48:
                    default:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 130f, 21f, 741f);
                        break;

                    case 49:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 120f, 21f, 741f);
                        break;

                    case 50:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 108f, 21f, 741f);
                        break;

                    case 51:
                        croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 92f, 21f, 741f);
                        break;
                    }

                    var reader   = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray());
                    var pageDict = reader.GetPageN(1);
                    pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangleCover);
                    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, dest_stream);
                    stamper.Close();
                    reader.Close();
                }
                catch (Exception excpt)
                {
                    System.Diagnostics.Debug.WriteLine(excpt);
                }
                return(dest_stream);
            }
        }
예제 #16
0
        public static bool AddBlankPage(string src)
        {
            string dest = (System.IO.Path.GetDirectoryName(src) + @"\temp " + DateTime.Now.ToString("ddMMyyyyhhmmssffff"));

            try
            {
                using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create))
                {
                    iTextSharp.text.pdf.PdfReader  reader  = new iTextSharp.text.pdf.PdfReader(src);
                    iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);
                    stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1));
                    stamper.Close();
                    reader.Close();
                }
                System.IO.File.Delete(src);
                System.IO.File.Move(dest, src);
                return(true);
            }
            catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); }
        }
 private System.IO.MemoryStream cropTypesetBrief(System.IO.MemoryStream orig_stream)
 {
     System.IO.MemoryStream dest_stream = null;
     try
     {
         dest_stream = new System.IO.MemoryStream();
         var croppedRectangle = new iTextSharp.text.pdf.PdfRectangle(377f, 189f, 0f, 792f);
         var reader           = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray());
         for (int i = 1; i <= reader.NumberOfPages; i++)
         {
             iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i);
             pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangle);
         }
         var stamper = new iTextSharp.text.pdf.PdfStamper(reader, dest_stream);
         stamper.Close();
         reader.Close();
     }
     catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); }
     return(dest_stream);
 }
예제 #18
0
        internal static byte[] InsertImageIntoPDF(byte[] file, Image QrImage, Image FontImage, int QPositionX = 30, int QPositionY = 675, int QWidth = 100, int QHeight = 100, int FPositionX = 450, int FPositionY = 50, int FWidth = 130, int FHeight = 15)
        {
            try
            {
                var pdfReader = new iTextSharp.text.pdf.PdfReader(file);
                using (var ms = new MemoryStream())
                {
                    using (var stamp = new iTextSharp.text.pdf.PdfStamper(pdfReader, ms))
                    {
                        var size = pdfReader.GetPageSize(1);
                        var page = pdfReader.NumberOfPages;

                        #region QrCode
                        System.Drawing.Imaging.ImageFormat QrImgformat = FormatImage(QrImage);
                        var pdfQrImage = iTextSharp.text.Image.GetInstance(QrImage, QrImgformat);
                        pdfQrImage.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                        pdfQrImage.SetAbsolutePosition(QPositionX, QPositionY);
                        pdfQrImage.ScaleToFit(QWidth, QHeight);
                        stamp.GetOverContent(page).AddImage(pdfQrImage);
                        #endregion

                        #region Font
                        System.Drawing.Imaging.ImageFormat fontImageFormat = FormatImage(FontImage);
                        var pdfFontImage = iTextSharp.text.Image.GetInstance(FontImage, fontImageFormat);
                        pdfFontImage.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                        pdfFontImage.SetAbsolutePosition(FPositionX, FPositionY);
                        pdfFontImage.ScaleToFit(FWidth, FHeight);
                        stamp.GetOverContent(page).AddImage(pdfFontImage);
                        #endregion
                    }
                    ms.Flush();
                    ms.GetBuffer();

                    return(ms.ToArray());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #19
0
 ///<summary>open file via iTextSharp and return pdf v1.4 for PdfSharp</summary>
 static MemoryStream GetCompartibleStream(string filename)
 {
     MemoryStream outputStream = new MemoryStream();
     iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(filename);
     iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream);
     pdfStamper.FormFlattening = true;
     pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
     pdfStamper.Writer.CloseStream = false;
     pdfStamper.Close();
     return outputStream;
 }
        public byte[] PrintSignToPDF_TextSharp(Stream File, String Firma, String Firmante)
        {
            MemoryStream outputPdfStream = new MemoryStream();
            PdfDocument document = PdfDocument.FromStream(File);
            document.SerialNumber = "s/va4uPX-1f/a0cHS-wcqFnYOT-gpOHk4qL-h5OAgp2C-gZ2KioqK";
            PdfFont pdfFont = document.CreateStandardFont(PdfStandardFont.Helvetica);
            byte[] pdfBuffer = document.WriteToMemory();
            var reader = new iTextSharp.text.pdf.PdfReader(pdfBuffer);
            var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

            iTextSharp.text.pdf.PdfContentByte pdfContentByte2;
            iTextSharp.text.Rectangle pageSize;
            try
            {
                pdfContentByte2 = stamper.GetOverContent(1);
                pageSize = reader.GetPageSizeWithRotation(1);
                pdfContentByte2.BeginText();
            }
            catch
            {
                pdfContentByte2 = stamper.GetOverContent(2);//PafinaFirma = 2
                pageSize = reader.GetPageSizeWithRotation(1);
                pdfContentByte2.BeginText();
            }

            //Firma = String.Format("{0} {1}", Firma, Firmante);
            string[] arrays = Firma.Split(' ');
            //iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
            iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont("c:/windows/fonts/arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, true);

            pdfContentByte2.SetFontAndSize(baseFont, 12);
            pdfContentByte2.SetRGBColorFill(0, 0, 0);

            StringBuilder bloqueFirma = new StringBuilder();
            int contador = 0;
            int saltoLineaPixeles = 5;
            for (int i = 0; i < arrays.Length; i++)
            {
                bloqueFirma.Append(arrays[i]);
                bloqueFirma.Append(" ");
                contador++;
                if ((contador == 35) || ((saltoLineaPixeles > 13) && (contador == 36)))
                {
                    pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                         pageSize.Width - (pageSize.Width / 5),
                                                        (pageSize.Height / 3) - saltoLineaPixeles - 110, 0);
                    contador = 0;
                    bloqueFirma = new StringBuilder();
                    saltoLineaPixeles = saltoLineaPixeles + 20;
                }
                else if ((i + 1) == arrays.Length)
                {
                    pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                         pageSize.Width - (pageSize.Width / 5),
                                                        (pageSize.Height / 3) - saltoLineaPixeles - 110, 0);
                    saltoLineaPixeles = saltoLineaPixeles + 20;
                }
            }

            pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, Firmante.ToString(),
                                                pageSize.Width - (pageSize.Width / 5),
                                            (pageSize.Height / 3) - saltoLineaPixeles - 110, 0);

            pdfContentByte2.EndText();

            stamper.Close();

            outputPdfStream.Close();
            outputPdfStream.Dispose();
            document.Close();

            return outputPdfStream.GetBuffer();
        }
예제 #21
0
        public static bool CombineBriefPages_AddingBlanks(
            List <CockleFilePdf> srcFiles, string src, TypeOfBindEnum bind)
        {
            // new attempt Dec 28, to account for divider pages (or any page without text)
            // text has to start on odd-numbered page, if followed by divider page

            // first, add 2 pages for each divider page, to account for front and back.
            // then, when everything is together, cycle through doc to add extra dividers...
            // ... so that text always falls on odd-numbered page


            // should work for both Saddle Stitch and Perfect Bind


            // create new list without cover, ordered by rank
            List <CockleFilePdf> files = new List <CockleFilePdf>(
                srcFiles
                .Where(f => f.FileType != SourceFileTypeEnum.Cover)
                .Where(f => f.FileType != SourceFileTypeEnum.InsideCv)
                .Where(f => f.FileType != SourceFileTypeEnum.SidewaysPage)
                .Where(f => f.FileType != SourceFileTypeEnum.Brief_Foldout)
                .Where(f => f.FileType != SourceFileTypeEnum.Brief_ZFold)
                .Where(f => f.FileType != SourceFileTypeEnum.App_Foldout)
                .Where(f => f.FileType != SourceFileTypeEnum.App_ZFold)
                .Where(f => f.FileType != SourceFileTypeEnum.Unrecognized)
                .OrderBy(f => f.Rank));

            if (files.Count < 1)
            {
                return(false);
            }

            // what if files.Count == 1 ??? just return ???

            int  pageCount         = 0;
            bool hasDividers       = false;
            bool firstAppFileFound = false;
            int  firstPageOfApp    = -1;

            try
            {
                using (var stream = new System.IO.FileStream(src, System.IO.FileMode.Create))
                {
                    // initiate iTextSharp processes
                    iTextSharp.text.Document    pdfdoc  = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
                    iTextSharp.text.pdf.PdfCopy pdfcopy = new iTextSharp.text.pdf.PdfCopy(pdfdoc, stream);
                    pdfdoc.Open();

                    // merge pdfs in folder
                    CockleFilePdf f;
                    for (int i = 0; i < files.Count; i++)
                    {
                        f = files[i];
                        // read file
                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(f.FullName);
                        int filePageCount = reader.NumberOfPages;

                        // set up pdfstamper
                        iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);

                        // look for divider pages here, add blank if exists
                        List <int> divider_pages = new List <int>();
                        iTextSharp.text.pdf.parser.PdfReaderContentParser parser = new iTextSharp.text.pdf.parser.PdfReaderContentParser(reader);
                        for (int j = 1; j <= reader.NumberOfPages; j++)
                        {
                            iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy extract = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                            var    extractedText = parser.ProcessContent(j, extract);
                            string textFromPage  = extractedText.GetResultantText();

                            int cnt     = textFromPage.ToCharArray().Count();
                            int mch_cnt = System.Text.RegularExpressions.Regex.Matches(textFromPage, @"A(PPENDIX|ppendix)").Count;

                            if (System.Text.RegularExpressions.Regex.Matches(textFromPage, @"\S").Count == 0)
                            {
                                // collect blank pages
                                divider_pages.Add(j);
                            }
                            else if (cnt < 50 && mch_cnt > 0)
                            {
                                // collect other divider pages
                                divider_pages.Add(j);
                            }
                        }
                        if (divider_pages.Count > 0)
                        {
                            hasDividers = true;

                            int k = 0; // adjust for total page number change
                            foreach (int page in divider_pages)
                            {
                                stamper.InsertPage(page + k, reader.GetPageSizeWithRotation(1));
                                filePageCount = reader.NumberOfPages;
                                k++;
                            }
                        }

                        // add blank page if needed to make even number
                        if (files[i].FileType == SourceFileTypeEnum.Index ||
                            files[i].FileType == SourceFileTypeEnum.Brief ||
                            files[i].FileType == SourceFileTypeEnum.App_Index ||
                            files[i].FileType == SourceFileTypeEnum.Motion ||
                            files[i].FileType == SourceFileTypeEnum.Divider_Page)
                        {
                            f.AssignNeedsBlankPage(files, reader.NumberOfPages);
                            if (f.NeedsBlankPage)
                            {
                                //PdfStamper stamper2 = new PdfStamper(reader, stream);
                                stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1));
                                filePageCount = reader.NumberOfPages;
                            }
                        }

                        // with last document in 'files', add extra pages to make divisible by 4
                        if (bind == TypeOfBindEnum.SaddleStitch && i == files.Count - 1)
                        {
                            if (bind == TypeOfBindEnum.SaddleStitch &&
                                (pageCount + reader.NumberOfPages) % 4 != 0)
                            {
                                //PdfStamper stamper3 = new PdfStamper(reader, stream);
                                while ((pageCount + reader.NumberOfPages) % 4 != 0)
                                {
                                    stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1));
                                }
                            }
                        }

                        // get first page of first app file
                        if (!firstAppFileFound && files[i].FileType == SourceFileTypeEnum.App_File)
                        {
                            firstAppFileFound = true;
                            firstPageOfApp    = pageCount + 1;
                        }

                        // add document to 'src'
                        pdfcopy.AddDocument(new iTextSharp.text.pdf.PdfReader(reader));
                        pageCount += reader.NumberOfPages;
                    }

                    pdfcopy.Close();
                    pdfdoc.CloseDocument();
                }

                // final cycle, if dividers, to make sure text starts on odd-sided pages
                if (bind == TypeOfBindEnum.PerfectBind && hasDividers)
                {
                    string dest = (System.IO.Path.GetDirectoryName(src) + @"\temp " + DateTime.Now.ToString("ddMMyyyyhhmmssffff"));

                    using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create))
                    {
                        iTextSharp.text.pdf.PdfReader  reader  = new iTextSharp.text.pdf.PdfReader(src);
                        iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);

                        // get all blank pages in appendix
                        iTextSharp.text.pdf.parser.PdfReaderContentParser parser = new iTextSharp.text.pdf.parser.PdfReaderContentParser(reader);
                        List <List <int> > groupsOfBlanks = new List <List <int> >();
                        List <int>         group_list     = new List <int>();
                        int x;
                        for (x = firstPageOfApp; x <= reader.NumberOfPages; x++)
                        {
                            iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy extract = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                            var    extractedText = parser.ProcessContent(x, extract);
                            string textFromPage  = extractedText.GetResultantText();
                            // find blank pages and cluster into group_list
                            if (System.Text.RegularExpressions.Regex.Matches(textFromPage, @"\S").Count == 0)
                            {
                                // capture blank page cluster (??? but what if only 1 page ???)
                                if (group_list.Count == 0 || group_list.Contains(x - 1))
                                {
                                    group_list.Add(x);
                                }
                            }
                            else
                            {
                                // find first page after cluster
                                if (group_list.Count > 0)
                                {
                                    if (group_list.Last() % 2 == 1)
                                    {
                                        // add blank page
                                        stamper.InsertPage(group_list.Last() + 1, reader.GetPageSizeWithRotation(1));
                                    }
                                }
                                // clear list
                                group_list.Clear();
                            }
                        }
                        stamper.Close();
                        reader.Close();
                    }
                    System.IO.File.Delete(src);
                    System.IO.File.Move(dest, src);
                }
            }
            catch (Exception excpt)
            {
                System.Diagnostics.Debug.WriteLine(excpt); return(false);
            }
            return(true);
        }
예제 #22
0
        /* ----------------------------------------------------------------- */
        ///
        /// AddInformation
        ///
        /// <summary>
        /// PDF ファイルに対して、引数に指定されたユーザ設定にしたがって
        /// 必要な情報を付与します。
        /// </summary>
        ///
        /// <remarks>
        /// iTextSharp を用いて以下の情報を付与します。
        ///
        /// - 文書プロパティ
        /// - 文書を開くためのパスワード (UserPassword)
        /// - 権限編集のためのパスワード (OwnerPassword)
        /// - 各種パーミッション
        /// </remarks>
        ///
        /* ----------------------------------------------------------------- */
        private bool AddInformation(UserSetting setting)
        {
            if (!CubePdf.Misc.File.Exists(setting.OutputPath))
            {
                return(false);
            }

            string tmp = Utility.WorkingDirectory + '\\' + System.IO.Path.GetRandomFileName();

            iTextSharp.text.pdf.PdfReader reader = null;
            bool status = true;

            try
            {
                CubePdf.Misc.File.Move(setting.OutputPath, tmp, true);
                reader = new iTextSharp.text.pdf.PdfReader(tmp);
                var writer = new iTextSharp.text.pdf.PdfStamper(reader,
                                                                new System.IO.FileStream(setting.OutputPath, System.IO.FileMode.Create), PdfVersionToiText(setting.PDFVersion));

                // 文書プロパティ
                Dictionary <string, string> info = new Dictionary <string, string>();
                info["Title"]    = setting.Document.Title;
                info["Author"]   = setting.Document.Author;
                info["Subject"]  = setting.Document.Subtitle;
                info["Keywords"] = setting.Document.Keyword;
                info["Creator"]  = Properties.Resources.ProductName;
                info["Producer"] = Properties.Resources.ProductName;
                writer.MoreInfo  = info;

                // デバッグログ
                var message = new System.Text.StringBuilder();
                message.AppendLine("iTextSharp.text.pdf.PdfStamper.MoreInfo");
                message.AppendLine(String.Format("\tTitle    = {0}", info["Title"]));
                message.AppendLine(String.Format("\tAuthor   = {0}", info["Author"]));
                message.AppendLine(String.Format("\tSubject  = {0}", info["Subject"]));
                message.Append(String.Format("\tKeywords = {0}", info["Keywords"]));
                _messages.Add(new Message(Message.Levels.Debug, message.ToString()));

                // パスワード and/or パーミッション
                string user  = !string.IsNullOrEmpty(setting.Password) ? setting.Password : string.Empty;
                string owner = !string.IsNullOrEmpty(setting.Permission.Password) ? setting.Permission.Password : string.Empty;
                if (string.IsNullOrEmpty(owner) && !string.IsNullOrEmpty(user))
                {
                    owner = user;
                }
                int permission = this.PermissionToiText(setting.Permission);
                if (!string.IsNullOrEmpty(user) || !string.IsNullOrEmpty(owner))
                {
                    writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STANDARD_ENCRYPTION_128, user, owner, permission);
                }

                writer.Close();
            }
            catch (Exception err)
            {
                _messages.Add(new Message(Message.Levels.Error, err));
                _messages.Add(new Message(Message.Levels.Debug, err));
                status = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (CubePdf.Misc.File.Exists(tmp))
                {
                    if (!CubePdf.Misc.File.Exists(setting.OutputPath))
                    {
                        CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                    }
                    else
                    {
                        var fi = new System.IO.FileInfo(setting.OutputPath);
                        if (fi.Length == 0)
                        {
                            CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                        }
                        else
                        {
                            CubePdf.Misc.File.Delete(tmp, false);
                        }
                    }
                }
            }

            return(status);
        }
예제 #23
-1
        /* ----------------------------------------------------------------- */
        ///
        /// AddInformation
        ///
        /// <summary>
        /// PDF ファイルに対して、引数に指定されたユーザ設定にしたがって
        /// 必要な情報を付与します。
        /// </summary>
        /// 
        /// <remarks>
        /// iTextSharp を用いて以下の情報を付与します。
        /// 
        /// - 文書プロパティ
        /// - 文書を開くためのパスワード (UserPassword)
        /// - 権限編集のためのパスワード (OwnerPassword)
        /// - 各種パーミッション
        /// </remarks>
        ///
        /* ----------------------------------------------------------------- */
        private bool AddInformation(UserSetting setting)
        {
            if (!CubePdf.Misc.File.Exists(setting.OutputPath)) return false;

            string tmp = Utility.WorkingDirectory + '\\' + System.IO.Path.GetRandomFileName();

            iTextSharp.text.pdf.PdfReader reader = null;
            bool status = true;
            try
            {
                CubePdf.Misc.File.Move(setting.OutputPath, tmp, true);
                reader = new iTextSharp.text.pdf.PdfReader(tmp);
                var writer = new iTextSharp.text.pdf.PdfStamper(reader,
                    new System.IO.FileStream(setting.OutputPath, System.IO.FileMode.Create), PdfVersionToiText(setting.PDFVersion));

                // 文書プロパティ
                Dictionary<string, string> info = new Dictionary<string, string>();
                info["Title"] = setting.Document.Title;
                info["Author"] = setting.Document.Author;
                info["Subject"] = setting.Document.Subtitle;
                info["Keywords"] = setting.Document.Keyword;
                info["Creator"] = Properties.Resources.ProductName;
                info["Producer"] = Properties.Resources.ProductName;
                writer.MoreInfo = info;

                // デバッグログ
                var message = new System.Text.StringBuilder();
                message.AppendLine("iTextSharp.text.pdf.PdfStamper.MoreInfo");
                message.AppendLine(String.Format("\tTitle    = {0}", info["Title"]));
                message.AppendLine(String.Format("\tAuthor   = {0}", info["Author"]));
                message.AppendLine(String.Format("\tSubject  = {0}", info["Subject"]));
                message.Append(    String.Format("\tKeywords = {0}", info["Keywords"]));
                _messages.Add(new Message(Message.Levels.Debug, message.ToString()));

                // パスワード and/or パーミッション
                string user  = !string.IsNullOrEmpty(setting.Password) ? setting.Password : string.Empty;
                string owner = !string.IsNullOrEmpty(setting.Permission.Password) ? setting.Permission.Password : string.Empty;
                if (string.IsNullOrEmpty(owner) && !string.IsNullOrEmpty(user)) owner = user;
                int permission = this.PermissionToiText(setting.Permission);
                if (!string.IsNullOrEmpty(user) || !string.IsNullOrEmpty(owner))
                {
                    writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STANDARD_ENCRYPTION_128, user, owner, permission);
                }

                writer.Close();
            }
            catch (Exception err)
            {
                _messages.Add(new Message(Message.Levels.Error, err));
                _messages.Add(new Message(Message.Levels.Debug, err));
                status = false;
            }
            finally
            {
                if (reader != null) reader.Close();
                if (CubePdf.Misc.File.Exists(tmp))
                {
                    if (!CubePdf.Misc.File.Exists(setting.OutputPath)) CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                    else
                    {
                        var fi = new System.IO.FileInfo(setting.OutputPath);
                        if (fi.Length == 0) CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                        else CubePdf.Misc.File.Delete(tmp, false);
                    }
                }
            }

            return status;
        }