Как вставить разметку HTML с помощью iTextSharp для создания PDF с использованием C #?
Я новичок вiTextSharp API
создаватьPDF
, я бы хотелCreate
аPDF
аналогично показано на следующем изображении: Я добавил таблицу (PdfPTable
) для отображения левой части (текст, кроме оранжевой рамки)
protected void CreatePDF()
{
//Create PDF slip
PdfPTable pdfTabdevices = new PdfPTable(2);
DataTable dt = Session["MyList"] as DataTable;
pdfTabdevices = GetDataFromSQLTable(dt);//Get the device lists
Document doc = new Document(iTextSharp.text.PageSize.A4, 20, 20, 42,35);//iTextSharp.text.PageSize.Letter, 10, 10, 42,35
int orderid = Session["OrderID"] != null ? Convert.ToInt32(Session["OrderID"]) : 0;
try
{
string pdfFilePath = Server.MapPath(".") + "/pdfdocs/" + orderid + ".pdf";
//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
doc.Open();//Open Document to write
Font font8 = FontFactory.GetFont("ARIAL", 7);
string imageFilePath = Server.MapPath(".") + "/images/Logo.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(100f, 50f);//jpg.ScaleToFit(280f, 260f);
//Give space before image
jpg.SpacingBefore = 30f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
doc.Add(jpg);
Phrase titl = new Phrase("\n\nPacking Slip\n");
titl.Font.SetStyle(Font.BOLD);
doc.Add(titl);
Phrase titlDesc = new Phrase("Place this slip inside the box with your device");
// titlDesc.Font.SetStyle(Font.BOLD);
doc.Add(titlDesc);
doc.Add(pdfTabdevices);
string expdate = Convert.ToString(DateTime.Now.Date);
Phrase expir = new Phrase("You have until " + expdate + " to ship your device.");
// titlDesc.Font.SetStyle(Font.BOLD);
doc.Add(expir);
Phrase note = new Phrase("\n\nIf you send your device after the expiration date we cannot honor your initial offer. We will not accept devices that have been reported lost or stolen.");
doc.Add(note);
}
catch (DocumentException docEx)
{
//handle pdf document exception if any
}
catch (IOException ioEx)
{
// handle IO exception
}
catch (Exception ex)
{
// ahndle other exception if occurs
}
finally
{
//Close document and writer
doc.Close();
}
}
protected PdfPTable GetDataFromSQLTable(DataTable dt)
{
PdfPTable table = new PdfPTable(2);
//actual width of table in points
table.TotalWidth = 500f;//216f;
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions - 2/3 & 1/3
float[] widths = new float[] { 2f, 1f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;
//leave a gap before and after the table
table.SpacingBefore = 20f;
table.SpacingAfter = 20f;
//PdfPCell cell2 = new PdfPCell(new Phrase("ITEM"));
PdfPCell cell2 = new PdfPCell(new Phrase("ITEM", new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK)));
cell2.Border = Rectangle.BOTTOM_BORDER;
cell2.BorderColor=Color.WHITE;
table.AddCell(cell2);
//PdfPCell cell = new PdfPCell(new Phrase("OFFER"));
PdfPCell cell = new PdfPCell(new Phrase("OFFER", new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK)));
cell2.Border = Rectangle.BOTTOM_BORDER;
cell.BorderColor = Color.WHITE;
//cell.Colspan = 2;
//cell.Border = 0;
//cell.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
table.AddCell(cell);
DataTable dtmain = new DataTable();
dtmain = dt;
double boxTotal = 0.00;
if (dtmain.Rows.Count > 0)
{
for (int i = 0; i < dtmain.Rows.Count; i++)
{
PdfPCell rcol1 =new PdfPCell(new Phrase(dtmain.Rows[i]["DeviceName"].ToString(), new Font(Font.HELVETICA, 10f, Font.NORMAL, Color.BLACK)));
rcol1.BorderColor = Color.WHITE;
table.AddCell(rcol1);
//table.AddCell(dtmain.Rows[i]["DeviceName"].ToString());
PdfPCell rcol2 = new PdfPCell(new Phrase("$" + dtmain.Rows[i]["Price"].ToString(), new Font(Font.HELVETICA, 10f, Font.NORMAL, Color.BLACK)));
rcol2.BorderColor = Color.WHITE;
table.AddCell(rcol2);
//table.AddCell("$" +dtmain.Rows[i]["Price"].ToString());
boxTotal+= Convert.ToDouble(dtmain.Rows[i]["Price"]);
}
}
PdfPCell rcolSecLast1 = new PdfPCell(new Phrase("---------------------------------------------------------------------------------", new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));
rcolSecLast1.BorderColor = Color.WHITE;
table.AddCell(rcolSecLast1);
PdfPCell rcolSecLast2 = new PdfPCell(new Phrase("--------------", new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));
rcolSecLast2.BorderColor = Color.WHITE;
table.AddCell(rcolSecLast2);
PdfPCell rcolLast = new PdfPCell(new Phrase("Total Offer :", new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));
rcolLast.BorderColor = Color.WHITE;
table.AddCell(rcolLast);
//table.AddCell("Total Offer :");
PdfPCell rcolLast1 = new PdfPCell(new Phrase(String.Format("{0:C}", boxTotal).ToString(), new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));
rcolLast1.BorderColor = Color.WHITE;
table.AddCell(rcolLast1);
//table.AddCell(String.Format("{0:C}",boxTotal).ToString());
return table;
}
Но яНевозможно нарисовать прямоугольник с оранжевой рамкой и его содержимое, используя'PdfPTable'
и выровняйте вправо, как показано на рис., Итак, есть ли другой способ ввода HTML-разметки в?PdfPTable
Пожалуйста, дайте предложения, чтобы сделать ..!
Примечание: когда пользователь завершает работу, файл PDF создается и сохраняется в папке, а не загружается или просматривается пользователем.
HTML-разметка:
<br>
<p>
<img src="/images/Logo.png" width="200px" height="100px"></p>
Packing slip
Place this slip inside the box with your device.
<strong> ITEM</strong>
<strong> OFFER</strong>
iPhone 5 32GB (AT&T)
$205.00
<strong>Total Offer: </strong>
<strong> $215.00</strong>
You have until 01/29/2014 to ship your device.
<p style="padding:10px;">
If you send your device after the expiration date we cannot honor your initial offer.
We will not accept devices that have been reported lost or stolen.</p>
<br>
<img src="../images/barcode.png" alt="barcode">
<img src="../images/pdfiphone.png" alt="iphone">
"Find my iPhone" must be turned off
This feature locks your device and will delay or reduce payment.
<strong>How to deactivate:</strong>
1. Tap the “settings” icon on your homescreen.
2. Tap iCloud from the settings menu.
3. If “Find My iPhone” is on, tap the slider to turn it off.
Могу ли я использовать выше HTML MARKUP и заменить строку и создать PDF и сохранить в папку без просмотра или загрузки пользователем?