I am using PDFsharp to create PDF files. My problem is when I lay down the lines of text to the PDF I get a single line only. So naturally, all of the text that fits on a the first line is visible since the other text has overflowed out of bounds.
Please see my code below:
private void createPdf2()
{
var title = DateTime.Now.ToString("MM-dd-yyyy-hh-m-ss") + "-" + txtPlazaNumber.Text + "-" + txtLaneNumber.Text;
var now = DateTime.Now;
var sb = new StringBuilder();
sb.AppendLine("Date: " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")).AppendLine(Environment.NewLine);
sb.AppendLine("Plaza Number: " + txtPlazaNumber.Text).AppendLine(Environment.NewLine);
sb.AppendLine("Lane Number: " + txtLaneNumber.Text).AppendLine(Environment.NewLine);
sb.AppendLine("RFID IP Address: " + txtRfidIpAddress.Text).AppendLine(Environment.NewLine);
sb.AppendLine("RFID Port: " + nRfidPort.Text).AppendLine(Environment.NewLine);
sb.AppendLine("TFI IP Address: " + txtTfiIpAddress.Text).AppendLine(Environment.NewLine);
sb.AppendLine("QR Port: " + nQrPort.Text).AppendLine(Environment.NewLine);
sb.AppendLine("Passed Tests").AppendLine();
foreach(var p in passedList)
{
sb.AppendLine("\t").Append(p.Trim()).AppendLine();
}
sb.AppendLine("Failed Tests").AppendLine();
foreach(var f in failedList)
{
sb.AppendLine("\f").Append(f.Trim()).AppendLine();
}
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = title;
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
graph.DrawString(sb.ToString(), font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
string pdfFilename = title + ".pdf";
pdf.Save(pdfFilename);
}
This is a little bit trickier to work around. You need an XTextFormatter, a XRect for the region which is available for the layouter and then call DrawString(…) on the formatter instead of the XGraphics object:
var formatter = new XTextFormatter(pageGraphics);
var layoutRectangle = new XRect(10, 10, page.Width, page.Height);
formatter.DrawString("Hello\r\nWorld", arial, XBrushes.Black, layoutRectangle);
http://development.wellisolutions.de/generating-pdf-with-pdfsharp/
Related
I have been reading that to put or remove the margins of a PDF the following line is used:
PageMargins = new Rotativa.Core.Options.Margins(0,0,0,0)
But, when I enter them I get the following:
'ViewAsPDF' does not contain a definition for 'PageMargins'
Any solution?
This is the complete code:
return new ViewAsPdf("Pdf48", c.cargarDatosPDF(solicitud))
{
CustomSwitches = "--header-html " + _headerUrl + " --header-spacing 0 " +
"--footer-html " + _footerUrl + " --footer-spacing 0",
PageMargins = new Rotativa.Core.Options.Margins(0,0,0,0)
};
Solution:
return new PartialViewAsPdf("Pdf48", c.cargarDatosPDF(solicitud))
{
RotativaOptions = new Rotativa.Core.DriverOptions
{
CustomSwitches = "--header-html " + _headerUrl + " --header-spacing 0 " +
"--footer-html " + _footerUrl + " --footer-spacing 0",
PageMargins = new Rotativa.Core.Options.Margins(0, 0, 0, 0)
}
};
This should help.
var pdfdoc= new Rotativa.ViewAsPdf(){
PageHeight=30.00,
PageWidth=30.00,
PageMargins=new Rotativa.Options.Margins(0,0,0,0)
};
I am developing a web application and one of its features is to generate a multiple certificate in a PDF file. There's no problem in generating a pdf but what I want to happen when generating a multiple certificate is to be in one pdf file only. I am just a beginner so I don't have much idea on doing that. Below is my code for generating a certificate. Thanks in advance!
protected void btnPdf_Click(object sender, EventArgs e)
{
string now = DateTime.Now.ToString("MM-dd-yyyy");
foreach (GridViewRow row in TraineeGrid.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked)
{
Label varName = (Label)row.FindControl("lbName");
string name = varName.Text;
Label varCourse = (Label)row.FindControl("lbCourse");
string course = varCourse.Text;
Label varCertNum = (Label)row.FindControl("lbCertNum");
string certNumber = varCertNum.Text;
Label varEndDate = (Label)row.FindControl("lbEndDate");
string endDate = varEndDate.Text;
DateTime date = DateTime.Parse(endDate);
string finalEDate = date.ToString("MMMM dd, yyyy");
Label varStartDate = (Label)row.FindControl("lbStartDate");
string startDate = varStartDate.Text;
DateTime date1 = DateTime.Parse(startDate);
string dateFileName = date1.ToString("MM-dd-yyyy");
string finalSDate = date1.ToString("MMMM dd, yyyy");
var checkedBoxes = TraineeGrid.Controls.OfType<CheckBox>().Count(c => chk.Checked);
try
{
Directory.CreateDirectory("D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\");
string inputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\CertificateLayout.pdf";
string outputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\"+name+"_" + course + "_"+dateFileName+".pdf";
// open the reader
PdfReader reader = new PdfReader(inputCertificate);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document();
// open the writer
FileStream fs = new FileStream(outputCertificate, FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, fs);
PdfContentByte cb = stamp.GetOverContent(1);
var pageSize = reader.GetPageSize(1);
ColumnText ct = new ColumnText(cb);
PdfCopy copy = new PdfCopy(document, fs);
document.Open();
Font font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 45, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 600f, 325f);
Paragraph certText = new Paragraph(new Phrase(20, name, font));
ct.AddElement(certText);
ct.Go();
Font font2 = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 19, iTextSharp.text.Color.GRAY);
ct.SetSimpleColumn(10f, 100f, 600f, 390f);
certText = new Paragraph(new Phrase("This is to certify that ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 297f);
certText = new Paragraph(new Phrase("has successfully completed the " + course + " at BASS Philippines RHQ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 240f);
certText = new Paragraph(new Phrase("From: " + finalSDate + "", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 216f);
certText = new Paragraph(new Phrase("To: " + finalEDate + "", font2));
ct.AddElement(certText);
ct.Go();
Font font3 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 500f, 192f);
certText = new Paragraph(new Phrase("Certificate Number: " + certNumber + "", font2));
ct.AddElement(certText);
ct.Go();
stamp.Close();
reader.Close();
fs.Close();
Process.Start(outputCertificate);
chk.Checked = false;
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: "+ ex.Message.ToString() +" \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
}
}
I am trying to save Barcode Image in database. What my code currently generating is just a long string of URL. My code is mentioned below:
string barCode = ds.Tables[0].Rows[0]["productId"].ToString();
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
// Font oFont = new Font("Free 3 of 9 Extended", 16);
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
**// I think Problem is here, in these lines //**
lblChkCopyIMAge.Text = imgBarCode.ToString();
}
placehod.Controls.Add(imgBarCode);
}
Can please anyone assist me to save complete Barcode image in specific folder and respective URL in database so that I can use it further. The code written above is just generating barcode image and a long string URL. When I saved it in database it is saving this string in URL: "System.Web.UI.WebControls.Label". I have used nvarchar(max) datatype to save ImageURL.
My code to Save in database is mentioned below:
string strcmd5 = "update product set symbology=" + "'" + "IDAutomationHC39M" + "'" + "," + "barcodeimage=" + "'" + lblChkCopyIMAge + "'" + "where productId=" + int.Parse(Label1.Text);
SqlCommand objsqlcmd5 = new SqlCommand(strcmd5, objsqlcon4);
int h = objsqlcmd5.ExecuteNonQuery();
objsqlcon4.Close();
if (h > 0)
{
Response.Write("Record has submitted Successfully");
ScriptManager.RegisterStartupScript(this, this.GetType(), "barcode", "alert('Saved Successfully');", true);
}
You're setting the value to a label control:
"barcodeimage=" + "'" + lblChkCopyIMAge + "'"
As an object, the default string representation for a label control is the name of the type. You probably want to use its .Text property instead?
"barcodeimage=" + "'" + lblChkCopyIMAge.Text + "'"
Note that you should also really look into using parameterized queries for your database interaction. As it stands right now, any user input used in this query is a SQL injection vulnerability.
I want the output format date like 14th may 2015. the th in 14 it should come with sup tag but sup tag is not accessing here. the output i am getting in ph102 variable. Getsuffix(csq.EventDate.Value.Day) in this only i am getting suffix of th st and rd for date
My code:
PdfPTable table9 = new PdfPTable(4);
table9.WidthPercentage = 99;
table9.DefaultCell.Border = 0;
table9.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Phrase ph101 = new Phrase("Event Date & Time", textFont2);
PdfPCell cellt1 = new PdfPCell(ph101);
cellt1.Border = PdfPCell.BOTTOM_BORDER + PdfPCell.LEFT_BORDER + PdfPCell.RIGHT_BORDER;
cellt1.PaddingTop = 0F;
cellt1.VerticalAlignment = Element.ALIGN_MIDDLE;
cellt1.HorizontalAlignment = Element.ALIGN_LEFT;
DateTime eventTime = DateTime.Today;
if (!string.IsNullOrEmpty(Convert.ToString(csq.EventTime)))
eventTime = DateTime.Today.Add(csq.EventTime.Value);
Phrase ph102;
if (!string.IsNullOrEmpty(csq.EventDate.ToString()))
{
ph102 = new Phrase(csq.EventDate.Value.Day + Getsuffix(csq.EventDate.Value.Day) + csq.EventDate.Value.ToString("MMM") + " " + csq.EventDate.Value.Year + " at " + eventTime.ToString("hh:mm tt"), textFont7);
}
else
{
ph102 = new Phrase();
}
PdfPCell cellt2 = new PdfPCell(ph102);
cellt2.Border = PdfPCell.BOTTOM_BORDER + PdfPCell.LEFT_BORDER + PdfPCell.RIGHT_BORDER;
cellt2.PaddingTop = 0F;
cellt2.VerticalAlignment = Element.ALIGN_MIDDLE;
cellt2.HorizontalAlignment = Element.ALIGN_LEFT;
When I read your question, I assume that you want something like this:
However, you are confusing people as is demonstrated in the comment from somebody who gives you a hint to use HTML to PDF. Your answer is "no sir it cant work" which is a strange answer, because it can work. It's just not what you meant when you talked about sup tag. At least, that's what I assume when I look at your code, I don't see any HTML.
In your code, you create a Phrase like this:
ph102 = new Phrase(csq.EventDate.Value.Day
+ Getsuffix(csq.EventDate.Value.Day)
+ csq.EventDate.Value.ToString("MMM")
+ " " + csq.EventDate.Value.Year
+ " at " + eventTime.ToString("hh:mm tt"), textFont7);
This complete Phrase is expressed in textFont7 which can't work in your case, because you want to use a smaller font for the "st", "nd", "rd" or "th".
You need to do something like this (see OrdinalNumbers for the full example):
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Font small = new Font(FontFamily.HELVETICA, 6);
Chunk st = new Chunk("st", small);
st.setTextRise(7);
Chunk nd = new Chunk("nd", small);
nd.setTextRise(7);
Chunk rd = new Chunk("rd", small);
rd.setTextRise(7);
Chunk th = new Chunk("th", small);
th.setTextRise(7);
Paragraph first = new Paragraph();
first.add("The 1");
first.add(st);
first.add(" of May");
document.add(first);
Paragraph second = new Paragraph();
second.add("The 2");
second.add(nd);
second.add(" and the 3");
second.add(rd);
second.add(" of June");
document.add(second);
Paragraph fourth = new Paragraph();
fourth.add("The 4");
fourth.add(rd);
fourth.add(" of July");
document.add(fourth);
document.close();
}
This is the Java code to create the PDF in the screen shot. You'll have to adapt your code so that it works in C#. As you can see, you can not just concatenate your strings using the + operator. You need to compose your Phrase or Paragraph using different Chunk objects. What you call "sup" is done by using a smaller font and a text rise.
the code below generate pdf documents:
using (FileStream fs = new FileStream("st.csv", FileMode.Open))
{
using (StreamReader configFile = new StreamReader(fs, System.Text.Encoding.GetEncoding("windows-1250")))
{
string line = string.Empty;
while ((line = configFile.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
line = line.Replace("\"", "");
string[] varible = line.Split(';');
string number = varible[0];
string stName = varible[1];
string ewidenceNumber = varible[2];
string fileName = "barcodes\\" + Encryption.RandomString(10, true) + ".png";
Generate(line, fileName);
PdfPTable Table = new PdfPTable(2);
Table.WidthPercentage = 100;
Table.SetWidths(new[] { 110f, 190f });
iTextSharp.text.Image barcode = iTextSharp.text.Image.GetInstance(fileName);
barcode.Border = 0;
barcode.ScalePercent(180f);
PdfPCell imageCell = new PdfPCell(barcode);
imageCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(imageCell);
PdfPCell descriptionCell = new PdfPCell(new Paragraph(
"Enterprise 1 \n\n" +
number + "\n\n" +
"Number1: " + stName + "\n\n" +
"Number2: " + ewidenceNumber, _standardFont));
descriptionCell.HorizontalAlignment = Element.ALIGN_CENTER;
descriptionCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(descriptionCell);
Table.KeepTogether = true;
Table.SpacingAfter = 10f;
doc.Add(Table);
}
}
}
}
and here is the problem: vertical and horizontal view in adobe acrobat displays correctly, but when I need to print labels with this information CITIZEN label printer always prints it in horizontal view. I can't adapt this data to print in correct orientation. Anyone has solution for this problem? Maybe I incorrectly rotate cells in table?
I would suggest you drop PDF and instead write to it's native format: http://www.citizen-europe.com/support/progman.htm
PDF printing support is supplied by the driver. If the driver doesn't know how to interpret the specific PDF commands then it's not going to work. Usually label printers don't provide very good driver support for anything but writing to their native format or emulating ZPL (zebra) and Datamax.