Пример #1
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();
                }
            }
        }
Пример #2
0
        private HttpResponseMessage GetPdfResponseForDictionary(Dictionary dictionary)
        {
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
            var memoryStream = new MemoryStream();

            iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);

            document.Open();
            string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

            iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(
                ARIALUNI_TFF, iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL);

            uint rowNumber = 1;

            foreach (var phrasesPair in dictionary.PhrasesPairs.OrderBy(p => p.FirstPhrase.Text))
            {
                document.Add(new iTextSharp.text.Paragraph(
                                 string.Format("{0}) {1} - {2}", rowNumber++, phrasesPair.FirstPhrase.Text, phrasesPair.SecondPhrase.Text),
                                 font));
            }
            document.NewPage();
            rowNumber = 1;
            foreach (var phrasesPair in dictionary.PhrasesPairs.OrderBy(p => p.SecondPhrase.Text))
            {
                document.Add(new iTextSharp.text.Paragraph(
                                 string.Format("{0}) {1} - {2}", rowNumber++, phrasesPair.SecondPhrase.Text, phrasesPair.FirstPhrase.Text),
                                 font));
            }
            document.AddAuthor(dictionary.OwnerId);
            document.Close();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new ByteArrayContent(memoryStream.ToArray());
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            string filename = string.Format("{0}.pdf", dictionary.Name);

            response.Content.Headers.ContentDisposition.FileName = Uri.EscapeUriString(filename);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return(response);
        }
Пример #3
0
        private void btnAddWatermark_Click(object sender, EventArgs e)
        {
            iTextSharp.text.pdf.BaseFont bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, false);

            stopWatch.Reset();
            stopWatch.Start();
            byte[] retValue = Watermark.AddWatermark(SourceFile, bf, txtWatermark.Text);
            stopWatch.Stop();
            lblITextSharpAllPages.Text = "Milliseconds: " + stopWatch.Elapsed.Milliseconds;
            string tmpFile = DestinationFile;

            File.WriteAllBytes(tmpFile, retValue);

            DialogResult dr = MessageBox.Show(MsgText, MsgCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dr == DialogResult.Yes)
            {
                Process.Start(tmpFile);
            }
        }
Пример #4
0
		private void _init()
		{
			if (fontpath != null && fontpath != string.Empty)
			{
				baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(fontpath, iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED);
			}
			else
			{
				baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
			}
			
			font = new iTextSharp.text.Font(baseFont, 10);
			iPDFContent.SetFontAndSize(font.BaseFont, font.Size);

			
			//20130607 :: add backgroung image
			if(_backgroundImage != null){
				DrawBackgroundImage(); // image for first page.
			}
			
			
			//20130613 :: set doc properties by default...
			try{PdfDoc.AddCreator( DocumentProperties.CreatorConstant );}catch(Exception){}
			
		}
Пример #5
0
        public static void ToPdfFile <T>(this System.Collections.Generic.IEnumerable <T> source, string path = null) where T : class
        {
            source.ThrowIfNull();
            iTextSharp.text.Document document = new iTextSharp.text.Document();

            if (string.IsNullOrWhiteSpace(path))
            {
                path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
            }

            path += $"\\{System.DateTime.Now.ToShortDateString().Replace('/', '-')}_table.pdf";
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(path, System.IO.FileMode.Create));
            document.Open();
            iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf",
                                                                                            iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE);
            var propertyInfoArray     = typeof(T).GetProperties().ToList();
            var properties            = propertyInfoArray.Select(x => x.Name).ToList();

            properties.ThrowIfNull(new System.Exception("Properties count is 0."));

            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(properties.Count);
            iTextSharp.text.pdf.PdfPCell  cell  = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase($"Database table writed at - {System.DateTime.Now.Date}", font))
            {
                Colspan             = properties.Count,
                HorizontalAlignment = 1,
                Border = 0
            };
            table.AddCell(cell);
            foreach (string item in properties)
            {
                cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(item, font));
                cell.BackgroundColor = iTextSharp.text.BaseColor.GREEN;
                table.AddCell(cell);
            }
            var listOfObjects = source.ToList();

            foreach (var item in listOfObjects)
            {
                foreach (System.Reflection.PropertyInfo propertyInfo in propertyInfoArray)
                {
                    string propertyName  = propertyInfo.Name;
                    object propertyValue = item?.GetType().GetProperty(propertyName)?.GetValue(item, null);
                    if (propertyValue is System.Collections.IEnumerable && !(propertyValue is string))
                    {
                        cell       = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("Collection", font));
                        font.Color = iTextSharp.text.BaseColor.RED;
                    }
                    else
                    {
                        bool   isNull = propertyValue.IsNull();
                        string text   = isNull ? "Empty" : propertyValue?.ToString();
                        cell                 = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase($"{text}", font));
                        font.Color           = iTextSharp.text.BaseColor.BLACK;
                        cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
                    }
                    table.AddCell(cell);
                    font.Color = iTextSharp.text.BaseColor.BLACK;
                }
            }
            bool added = document.Add(table);

            if (!added)
            {
                throw new System.Exception("Table wasn't added to document. Please verify your object.");
            }

            document.Close();
        }
Пример #6
0
        public static string PrintPDFResize(string fileNamePath)
        {
            Debug.Log("CashmaticApp", "PrintPDFResize");
            string fileDirectory = Path.GetDirectoryName(fileNamePath);
            string fileName      = Path.GetFileNameWithoutExtension(fileNamePath);
            string newFile       = fileDirectory + "\\" + fileName + "_print.pdf";



            try
            {
                // open the reader
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNamePath);

                iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
                //Document document = new Document(size);
                iTextSharp.text.Document document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(size.Width + 15, size.Height + Global.CardPaymentPrintPageSizeAddHeight));

                // open the writer
                FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs);
                document.Open();

                // the pdf content
                iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                if (Global.cardholderReceipt != "")
                {
                    // select the font properties
                    iTextSharp.text.pdf.BaseFont bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    cb.SetColorFill(iTextSharp.text.BaseColor.BLACK);
                    cb.SetFontAndSize(bf, 8);

                    int StartAt = Global.CardPaymentPrintStartAt + Global.CardPaymentPrintPageSizeAddHeight;

                    foreach (string line in Global.cardholderReceipt.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                    {
                        // write the text in the pdf content
                        cb.BeginText();
                        // put the alignment and coordinates here
                        cb.ShowTextAligned(0, line, Global.CardPaymentPrintLeft, StartAt, 0);
                        cb.EndText();
                        StartAt = StartAt - Global.CardPaymentPrintLineHeight;
                    }
                }

                //// create the new page and add it to the pdf
                iTextSharp.text.pdf.PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 10, +Global.CardPaymentPrintPageSizeAddHeight);

                // close the streams and voilá the file should be changed :)
                document.Close();
                fs.Close();
                writer.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                Debug.Log("CashmaticApp", ex.ToString());
            }

            return(newFile);
        }
Пример #7
0
 /// <summary>
 /// iTextSharp字体设置
 /// </summary>
 /// <param name="fontPath"></param>
 /// <param name="fontSize"></param>
 /// <param name="fontStyle"></param>
 private static iTextSharp.text.Font BaseFont(string fontPath, float fontSize, int fontStyle)
 {
     iTextSharp.text.pdf.BaseFont chinese = iTextSharp.text.pdf.BaseFont.CreateFont(fontPath, iTextSharp.text.pdf.BaseFont.IDENTITY_H, true);
     iTextSharp.text.Font         pdfFont = new iTextSharp.text.Font(chinese, fontSize, fontStyle);
     return(pdfFont);
 }
Пример #8
0
        public static byte[] CreatePdfDataFromAssignment(SqlConnection conn, SqlTransaction trans, Guid assignmentId)
        {
            string   OrderName = "", LaboratoryName = "", ResponsibleName = "", CustomerName = "", CustomerCompany = "", CustomerAddress = "";
            PdfImage labLogo = null;

            using (SqlDataReader reader = DB.GetDataReader(conn, trans, "csp_select_assignment_flat", CommandType.StoredProcedure, new SqlParameter("@id", assignmentId)))
            {
                if (reader.HasRows)
                {
                    reader.Read();

                    OrderName       = reader.GetString("name");
                    LaboratoryName  = reader.GetString("laboratory_name");
                    ResponsibleName = reader.GetString("account_name");
                    CustomerName    = reader.GetString("customer_contact_name");
                    CustomerCompany = reader.GetString("customer_company_name");
                    CustomerAddress = reader.GetString("customer_contact_address");
                }
            }

            Guid labId = (Guid)DB.GetScalar(conn, trans, "select laboratory_id from assignment where id = @id", CommandType.Text, new SqlParameter("@id", assignmentId));

            if (Utils.IsValidGuid(labId))
            {
                using (SqlDataReader reader = DB.GetDataReader(conn, trans, "select laboratory_logo from laboratory where id = @id", CommandType.Text, new SqlParameter("@id", labId)))
                {
                    if (reader.HasRows)
                    {
                        reader.Read();

                        if (DB.IsValidField(reader["laboratory_logo"]))
                        {
                            labLogo = PdfImage.GetInstance((byte[])reader["laboratory_logo"]);
                        }
                    }
                }
            }

            byte[]       pdfData  = null;
            PdfDocument  document = null;
            MemoryStream ms       = null;

            try
            {
                ms       = new MemoryStream();
                document = new PdfDocument();
                PdfWriter writer = PdfWriter.GetInstance(document, ms);

                document.Open();

                PdfContentByte cb = writer.DirectContent;

                cb.BeginText();

                PdfBaseFont baseFont = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_ROMAN, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED);
                PdfBaseFont baseFontBold = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_BOLD, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED);
                PdfBaseFont baseFontItalic = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_ITALIC, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED);
                float       fontSize = 10, fontSizeHeader = 14;
                float       margin = 50;
                float       leftCursor = margin, topCursor = document.Top - margin, lineSpace = 13;
                bool        hasLogos = false;

                if (labLogo != null)
                {
                    CropImageToHeight(labLogo, 64f);
                    labLogo.SetAbsolutePosition(leftCursor, topCursor);
                    document.Add(labLogo);
                    hasLogos = true;
                }

                if (hasLogos)
                {
                    topCursor -= labLogo.ScaledHeight;
                }

                cb.SetFontAndSize(baseFontBold, fontSizeHeader);
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "OPPDRAGSOVERSIKT", leftCursor, topCursor, 0);
                cb.SetFontAndSize(baseFont, fontSize);
                topCursor -= lineSpace * 2;
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdrag: " + OrderName, leftCursor, topCursor, 0);
                topCursor -= lineSpace;
                string cust = CustomerName;
                if (!String.IsNullOrEmpty(CustomerCompany))
                {
                    cust += ", " + CustomerCompany;
                }
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver: " + cust, leftCursor, topCursor, 0);
                topCursor -= lineSpace;
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, CustomerAddress, leftCursor, topCursor, 0);
                topCursor -= lineSpace;
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Laboratorium/Kontaktperson: " + LaboratoryName + " / " + ResponsibleName, leftCursor, topCursor, 0);
                topCursor -= lineSpace * 4;
                cb.SetFontAndSize(baseFontBold, fontSizeHeader);
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Måleresultater", leftCursor, topCursor, 0);
                cb.EndText();

                topCursor -= lineSpace;

                PdfPTable table = new PdfPTable(13);
                table.TotalWidth = document.GetRight(margin) - document.GetLeft(margin);

                PdfPCell cell = new PdfPCell(GetHeaderPhrase("Analysis"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Sample Type"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("P.Status"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("A.Status"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Method"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Nuclide"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Activity"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Act.Unc."));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Act.Appr."));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("MDA"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("MDA Appr."));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Reportable"));
                table.AddCell(cell);
                cell = new PdfPCell(GetHeaderPhrase("Accredited"));
                table.AddCell(cell);

                string query = @"
select 
    s.number as 'sample', 
    st.name as 'sample_type_name',
    sc.name as 'sample_component_name',
	p.number as 'preparation', 
    pm.name_short as 'preparation_method', 
    p.workflow_status_id as 'preparation_wfstatus', 
	a.number as 'analysis',     
    a.workflow_status_id as 'analysis_wfstatus', 
	am.name_short as 'analysis_method', 
	n.name as 'nuclide_name', 
	ar.activity as 'act', 
	ar.activity_uncertainty_abs as 'act.unc', 
	ar.activity_approved as 'act.appr', 
	ar.detection_limit as 'det.lim', 
	ar.detection_limit_approved as 'det.lim.appr', 
	ar.reportable, 
	ar.accredited
from sample s
    inner join sample_type st on st.id = s.sample_type_id
    left outer join sample_component sc on sc.id = s.sample_component_id
    inner join preparation p on p.sample_id = s.id and p.instance_status_id <= 1
    inner join preparation_method pm on pm.id = p.preparation_method_id
    inner join analysis a on a.preparation_id = p.id and a.instance_status_id <= 1 and a.assignment_id = @assignment_id
    inner join analysis_result ar on ar.analysis_id = a.id
    inner join analysis_method am on am.id = a.analysis_method_id
    inner join nuclide n on n.id = ar.nuclide_id
order by s.number, p.number, a.number
";
                int    nRows = 1;
                using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] {
                    new SqlParameter("@assignment_id", assignmentId)
                }))
                {
                    while (reader.Read())
                    {
                        int    pwfstat  = reader.GetInt32("preparation_wfstatus");
                        string spwfstat = "Unknown";
                        switch (pwfstat)
                        {
                        case WorkflowStatus.Construction:
                            spwfstat = "Construction";
                            break;

                        case WorkflowStatus.Complete:
                            spwfstat = "Complete";
                            break;

                        case WorkflowStatus.Rejected:
                            spwfstat = "Rejected";
                            break;
                        }

                        int    awfstat  = reader.GetInt32("analysis_wfstatus");
                        string sawfstat = "Unknown";
                        switch (awfstat)
                        {
                        case WorkflowStatus.Construction:
                            sawfstat = "Construction";
                            break;

                        case WorkflowStatus.Complete:
                            sawfstat = "Complete";
                            break;

                        case WorkflowStatus.Rejected:
                            sawfstat = "Rejected";
                            break;
                        }

                        string sact = "";
                        if (DB.IsValidField(reader["act"]))
                        {
                            sact = reader.GetDouble("act").ToString(Utils.ScientificFormat);
                        }

                        string sactunc = "";
                        if (DB.IsValidField(reader["act.unc"]))
                        {
                            sactunc = reader.GetDouble("act.unc").ToString(Utils.ScientificFormat);
                        }

                        string sdetlim = "";
                        if (DB.IsValidField(reader["det.lim"]))
                        {
                            sdetlim = reader.GetDouble("det.lim").ToString(Utils.ScientificFormat);
                        }

                        cell = new PdfPCell(GetCellPhrase(reader.GetString("sample") + "/" + reader.GetString("preparation") + "/" + reader.GetString("analysis")));
                        table.AddCell(cell);
                        string sampleType = reader.GetString("sample_type_name");
                        if (DB.IsValidField(reader["sample_component_name"]))
                        {
                            sampleType += " / " + reader.GetString("sample_component_name");
                        }
                        cell = new PdfPCell(GetCellPhrase(sampleType));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(spwfstat));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(sawfstat));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(reader.GetString("preparation_method") + " / " + reader.GetString("analysis_method")));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(reader.GetString("nuclide_name")));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(sact));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(sactunc));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(reader.GetString("act.appr")));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(sdetlim));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(reader.GetString("det.lim.appr")));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(reader.GetString("reportable")));
                        table.AddCell(cell);
                        cell = new PdfPCell(GetCellPhrase(reader.GetString("accredited")));
                        table.AddCell(cell);
                        nRows++;
                    }
                }

                float currHeight = topCursor;
                int   currRow = 0, pageRows = 0;

                for (int i = 0; i < nRows; i++)
                {
                    currHeight -= table.GetRowHeight(i);
                    pageRows++;

                    if (currHeight <= document.GetBottom(10f))
                    {
                        table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb);
                        document.NewPage();

                        currRow   += pageRows;
                        currHeight = topCursor = document.GetTop(10f);
                        pageRows   = 0;
                    }
                }

                if (pageRows > 0)
                {
                    table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb);
                    document.NewPage();
                }
            }
            finally
            {
                document?.Close();
                if (ms != null)
                {
                    pdfData = ms.GetBuffer();
                }
            }

            return(pdfData);
        }
Пример #9
0
        public static byte[] CreatePdfDataFromDataGridView(DataGridView grid, int startColumn, int endColumn, string title)
        {
            byte[]       pdfData  = null;
            PdfDocument  document = null;
            MemoryStream ms       = null;

            try
            {
                ms       = new MemoryStream();
                document = new PdfDocument();
                PdfWriter writer = PdfWriter.GetInstance(document, ms);

                document.Open();

                PdfContentByte cb = writer.DirectContent;

                cb.BeginText();

                PdfBaseFont baseFontBold   = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_BOLD, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED);
                float       fontSizeHeader = 14f;
                float       topCursor      = document.GetTop(10f);

                cb.SetFontAndSize(baseFontBold, fontSizeHeader);
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, title, document.GetLeft(10f), topCursor, 0);
                topCursor -= 20f;
                cb.EndText();

                int nCols = endColumn - startColumn;

                PdfPTable table = new PdfPTable(nCols);
                table.TotalWidth = document.GetRight(10) - document.GetLeft(10);

                for (int i = startColumn; i < endColumn; i++)
                {
                    PdfPCell cell = new PdfPCell(GetHeaderPhrase(grid.Columns[i].HeaderText));
                    cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    cell.VerticalAlignment   = PdfPCell.ALIGN_LEFT;
                    table.AddCell(cell);
                }

                for (int i = 0; i < grid.Rows.Count; i++)
                {
                    for (int j = startColumn; j < endColumn; j++)
                    {
                        PdfPCell cell = new PdfPCell(GetCellPhrase(grid.Rows[i].Cells[j].FormattedValue.ToString()));
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.VerticalAlignment   = PdfPCell.ALIGN_LEFT;
                        table.AddCell(cell);
                    }
                }

                float currHeight = topCursor;
                int   currRow = 0, pageRows = 0, nRows = grid.Rows.Count + 1;

                for (int i = 0; i < nRows; i++)
                {
                    currHeight -= table.GetRowHeight(i);
                    pageRows++;

                    if (currHeight <= document.GetBottom(10f))
                    {
                        table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb);
                        document.NewPage();

                        currRow   += pageRows;
                        currHeight = topCursor = document.GetTop(10f);
                        pageRows   = 0;
                    }
                }

                if (pageRows > 0)
                {
                    table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb);
                    document.NewPage();
                }
            }
            finally
            {
                document?.Close();
                if (ms != null)
                {
                    pdfData = ms.GetBuffer();
                }
            }

            return(pdfData);
        }
Пример #10
0
        /// <summary>
        /// Get the converted font.
        /// </summary>
        /// <returns>The text font.</returns>
        private iTextSharp.text.pdf.BaseFont GetBaseFont()
        {
            iTextSharp.text.pdf.BaseFont font = null;

            // Select the font family.
            switch (_fontFamily)
            {
            case FontFamily.Courier:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.COURIER,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Courier_Bold:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.COURIER_BOLD,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Courier_BoldOblique:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.COURIER_BOLDOBLIQUE,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Courier_Oblique:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.COURIER_OBLIQUE,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Helvetica:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.HELVETICA,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Helvetica_Bold:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Helvetica_BoldOblique:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.HELVETICA_BOLDOBLIQUE,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Helvetica_Oblique:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.HELVETICA_OBLIQUE,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Symbol:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.SYMBOL,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Times_Bold:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.TIMES_BOLD,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Times_BoldItalic:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.TIMES_BOLDITALIC,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Times_Italic:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.TIMES_ITALIC,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Times_Roman:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.TIMES_ROMAN,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.ZapfDingbats:
                font = iTextSharp.text.pdf.BaseFont.CreateFont(
                    iTextSharp.text.pdf.BaseFont.ZAPFDINGBATS,
                    iTextSharp.text.pdf.BaseFont.WINANSI,
                    _embedded);
                break;

            case FontFamily.Undefined:
            default:
                // Select the font encoding.
                switch (_fontEncoding)
                {
                case FontEncoding.CP1250:
                    font = iTextSharp.text.pdf.BaseFont.CreateFont(
                        _fontName,
                        iTextSharp.text.pdf.BaseFont.CP1250,
                        _embedded);
                    break;

                case FontEncoding.CP1252:
                    font = iTextSharp.text.pdf.BaseFont.CreateFont(
                        _fontName,
                        iTextSharp.text.pdf.BaseFont.CP1252,
                        _embedded);
                    break;

                case FontEncoding.CP1257:
                    font = iTextSharp.text.pdf.BaseFont.CreateFont(
                        _fontName,
                        iTextSharp.text.pdf.BaseFont.CP1257,
                        _embedded);
                    break;

                case FontEncoding.MACROMAN:
                    font = iTextSharp.text.pdf.BaseFont.CreateFont(
                        _fontName,
                        iTextSharp.text.pdf.BaseFont.MACROMAN,
                        _embedded);
                    break;

                case FontEncoding.WINANSI:
                    font = iTextSharp.text.pdf.BaseFont.CreateFont(
                        _fontName,
                        iTextSharp.text.pdf.BaseFont.WINANSI,
                        _embedded);
                    break;

                case FontEncoding.Undefined:
                default:
                    font = iTextSharp.text.pdf.BaseFont.CreateFont(
                        _fontName,
                        _encoding,
                        _embedded);
                    break;
                }
                break;
            }

            // Return the base font;
            return(font);
        }