Hello everyone i am working on a project in which i have to export some data into a ppt using openxml on button click.Here is my code for the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.Extensions1;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
namespace TableInPPT
{
public partial class _Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string templateFile = Server.MapPath("~/Template/Sample.potm");
string presentationFile = Server.MapPath("~/Template/SmapleNew.pptx");
PotxToPptx(templateFile, presentationFile);
//using (PresentationDocument themeDocument = PresentationDocument.Open(templateFile, false))
using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, true))
{
AddImage(prstDoc);
AddTable(prstDoc);
}
string itemname = "SmapleNew.pptx";
Response.Clear();
Response.ContentType = "pptx";
Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
Response.BinaryWrite(System.IO.File.ReadAllBytes(presentationFile));
Response.Flush();
Response.End();
}
private void PotxToPptx(string templateFile, string presentationFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (PresentationDocument pptPackage = PresentationDocument.Open(presentationStream, true))
{
pptPackage.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = pptPackage.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
presPart.Presentation.Save();
}
File.WriteAllBytes(presentationFile, presentationStream.ToArray());
}
private void AddTable(PresentationDocument prstDoc)
{
// Add one slide
Slide slide = prstDoc.PresentationPart.InsertSlide1("Custom Layout", 2);
Shape tableShape = slide.CommonSlideData.ShapeTree.ChildElements.OfType<Shape>()
.Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder").SingleOrDefault();
if (tableShape == null) return;
// Create Graphic Frame
OpenXmlCompositeElement gElement = GetGraphicFrame(tableShape);
// Create a (6x3)Table
ODrawing.Table openXmlTable = GetSmapleTable();
// add table to graphic element
gElement.GetFirstChild<ODrawing.Graphic>().GetFirstChild<ODrawing.GraphicData>().Append(openXmlTable);
slide.CommonSlideData.ShapeTree.Append(gElement);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(tableShape);
prstDoc.PresentationPart.Presentation.Save();
}
private void AddImage(PresentationDocument prstDoc)
{
string imgpath = Server.MapPath("~/Template/xxxx.jpg");
Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content", 2);
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = 2, Name = "Title" },
new NonVisualShapeDrawingProperties(new ODrawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new ODrawing.BodyProperties(),
new ODrawing.ListStyle(),
new ODrawing.Paragraph(new ODrawing.Run(new ODrawing.Text() { Text = "Trade Promotion Graph " })));
Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
Picture pic = slide.AddPicture(shape, imgpath);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
slide.Save();
prstDoc.PresentationPart.Presentation.Save();
}
private ODrawing.Table GetSmapleTable()
{
ODrawing.Table table = new ODrawing.Table();
ODrawing.TableProperties tableProperties = new ODrawing.TableProperties();
ODrawing.TableStyleId tableStyleId = new ODrawing.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
//tableStyleId.Text = "{D27102A9-8310-4765-A935-A1911B00CA55}";
tableProperties.Append(tableStyleId);
ODrawing.TableGrid tableGrid = new ODrawing.TableGrid();
ODrawing.GridColumn gridColumn1 = new ODrawing.GridColumn() { Width = 2600000L};
ODrawing.GridColumn gridColumn2 = new ODrawing.GridColumn() { Width = 2600000L };
//ODrawing.GridColumn gridColumn3 = new ODrawing.GridColumn() { Width = 1071600L };
//ODrawing.GridColumn gridColumn4 = new ODrawing.GridColumn() { Width = 1571600L };
//ODrawing.GridColumn gridColumn5 = new ODrawing.GridColumn() { Width = 771600L };
//ODrawing.GridColumn gridColumn6 = new ODrawing.GridColumn() { Width = 1071600L };
tableGrid.Append(gridColumn1);
tableGrid.Append(gridColumn2);
//tableGrid.Append(gridColumn3);
//tableGrid.Append(gridColumn4);
//tableGrid.Append(gridColumn5);
//tableGrid.Append(gridColumn6);
table.Append(tableProperties);
table.Append(tableGrid);
for (int row = 1; row <= 5; row++)
{
string text1 = "PARAMETERS";
string text2="VALUES";
if (row == 2)
{
text1 =Label1.Text ;
text2 = TextBox1.Text;
}
if (row == 3)
{
text1 = Label2.Text;
text2 = TextBox2.Text;
}
if (row == 4)
{
text1 = Label3.Text;
text2 = TextBox3.Text;
}
if (row == 5)
{
text1 = Label4.Text;
text2 = TextBox4.Text;
}
ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000},
new ODrawing.Text(text1)))),
new ODrawing.TableCellProperties()));
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000 },
new ODrawing.Text(text2)))),
new ODrawing.TableCellProperties()));
ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
schemeColor.Append(luminanceModulation);
solidFill.Append(schemeColor);
table.Append(tableRow);
}
//for (int row = 1; row <= 3; row++)
//{
// ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
// for (int column = 1; column <= 6; column++)
// {
// ODrawing.TableCell tableCell = new ODrawing.TableCell();
// TextBody textBody = new TextBody() { BodyProperties = new ODrawing.BodyProperties(), ListStyle = new ODrawing.ListStyle() };
// ODrawing.Paragraph paragraph = new ODrawing.Paragraph();
// ODrawing.Run run = new ODrawing.Run();
// ODrawing.RunProperties runProperties = new ODrawing.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
// ODrawing.Text text = new ODrawing.Text();
// text.Text = "Smaple Text";
// run.Append(runProperties);
// run.Append(text);
// ODrawing.EndParagraphRunProperties endParagraphRunProperties = new ODrawing.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
// paragraph.Append(run);
// paragraph.Append(endParagraphRunProperties);
// textBody.Append(paragraph);
// ODrawing.TableCellProperties tableCellProperties = new ODrawing.TableCellProperties();
// ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
// ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
// ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
// schemeColor.Append(luminanceModulation);
// solidFill.Append(schemeColor);
// tableCellProperties.Append(solidFill);
// tableCell.Append(textBody);
// tableCell.Append(tableCellProperties);
// tableRow.Append(tableCell);
// if (column == 1 && row == 1)
// {
// tableRow.Append(CreateTextCell("category"));
// }
// }
// }
return table;
}
static ODrawing.TableCell CreateTextCell(string text)
{
ODrawing.TableCell tc = new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.Text(text)))),
new ODrawing.TableCellProperties());
return tc;
}
private static OpenXmlCompositeElement GetGraphicFrame(Shape refShape)
{
GraphicFrame graphicFrame = new GraphicFrame();
int contentPlaceholderCount = 0;
UInt32Value graphicFrameId = 1000;
NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties();
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties()
{
Id = ++graphicFrameId,
Name = "Table" + contentPlaceholderCount.ToString(),
};
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties = new NonVisualGraphicFrameDrawingProperties();
ODrawing.GraphicFrameLocks graphicFrameLocks = new ODrawing.GraphicFrameLocks() { NoGrouping = true };
nonVisualGraphicFrameDrawingProperties.Append(graphicFrameLocks);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape = new PlaceholderShape() { Index = graphicFrameId };
applicationNonVisualDrawingProperties.Append(placeholderShape);
nonVisualGraphicFrameProperties.Append(nonVisualDrawingProperties);
nonVisualGraphicFrameProperties.Append(nonVisualGraphicFrameDrawingProperties);
nonVisualGraphicFrameProperties.Append(applicationNonVisualDrawingProperties);
Transform transform = new Transform()
{
Offset = new ODrawing.Offset() { X = refShape.ShapeProperties.Transform2D.Offset.X, Y = refShape.ShapeProperties.Transform2D.Offset.Y },
Extents = new ODrawing.Extents() { Cx = refShape.ShapeProperties.Transform2D.Extents.Cx, Cy = refShape.ShapeProperties.Transform2D.Extents.Cy }
};
ODrawing.Graphic graphic = new ODrawing.Graphic();
ODrawing.GraphicData graphicData = new ODrawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" };
graphic.Append(graphicData);
graphicFrame.Append(nonVisualGraphicFrameProperties);
graphicFrame.Append(transform);
graphicFrame.Append(graphic);
return graphicFrame;
}
}
}
Please note that the template used is a sample template containing two slides only i.e. one title slide and one more blank side with a wordart having some random text written on it.
Also the table is filled with data from 4 textboxes present on the aspx page.
And here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
namespace DocumentFormat.Extensions1
{
public static class Extensions1
{
internal static Slide InsertSlide(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
public static Slide InsertSlide1(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideMasterPart smPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
//SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
sPart.AddPart<SlideLayoutPart>(slPart);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
internal static int ReorderSlides(PresentationPart presentationPart, int currentSlidePosition, int newPosition)
{
int returnValue = -1;
if (newPosition == currentSlidePosition) { return returnValue; }
int slideCount = presentationPart.SlideParts.Count();
if (slideCount == 0) { return returnValue; }
int maxPosition = slideCount - 1;
CalculatePositions(ref currentSlidePosition, ref newPosition, maxPosition);
if (newPosition != currentSlidePosition)
{
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
SlideIdList slideIdList = presentation.SlideIdList;
SlideId sourceSlide = (SlideId)(slideIdList.ChildElements[currentSlidePosition]);
SlideId targetSlide = (SlideId)(slideIdList.ChildElements[newPosition]);
sourceSlide.Remove();
if (newPosition > currentSlidePosition)
{
slideIdList.InsertAfter(sourceSlide, targetSlide);
}
else
{
slideIdList.InsertBefore(sourceSlide, targetSlide);
}
returnValue = newPosition;
}
presentationPart.Presentation.Save();
return returnValue;
}
private static void CalculatePositions(ref int originalPosition, ref int newPosition, int maxPosition)
{
if (originalPosition < 0)
{
originalPosition = maxPosition;
}
if (newPosition < 0)
{
newPosition = maxPosition;
}
if (originalPosition > maxPosition)
{
originalPosition = maxPosition;
}
if (newPosition > maxPosition)
{
newPosition = maxPosition;
}
}
private static Slide GetSlideByRelationshipId(PresentationPart presentationPart, DocumentFormat.OpenXml.StringValue relId)
{
SlidePart slidePart = presentationPart.GetPartById(relId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
{
Picture picture = new Picture();
string embedId = string.Empty;
UInt32Value picId = 10001U;
string name = string.Empty;
if (slide.Elements<Picture>().Count() > 0)
{
picId = ++slide.Elements<Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
}
name = "image" + picId.ToString();
embedId = "rId" + (slide.Elements<Picture>().Count() + 915).ToString(); // some value
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
{
NonVisualDrawingProperties = new NonVisualDrawingProperties() { Name = name, Id = picId, Title = name },
NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() { PictureLocks = new Drawing.PictureLocks() { NoChangeAspect = true } },
ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties() { UserDrawn = true }
};
BlipFill blipFill = new BlipFill() { Blip = new Drawing.Blip() { Embed = embedId } };
Drawing.Stretch stretch = new Drawing.Stretch() { FillRectangle = new Drawing.FillRectangle() };
blipFill.Append(stretch);
ShapeProperties shapeProperties = new ShapeProperties()
{
Transform2D = new Drawing.Transform2D()
{
Offset = new Drawing.Offset() { X = 1554691, Y = 1600200 },
Extents = new Drawing.Extents() { Cx = 6034617, Cy = 4525963 }
}
};
Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry() { Preset = Drawing.ShapeTypeValues.Rectangle };
Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.Append(picture);
// Add Image part
slide.AddImagePart(embedId, imageFile);
slide.Save();
return picture;
}
private static void AddImagePart(this Slide slide, string relationshipId, string imageFile)
{
ImagePart imgPart = slide.SlidePart.AddImagePart(GetImagePartType(imageFile), relationshipId);
using (FileStream imgStream = File.Open(imageFile, FileMode.Open))
{
imgPart.FeedData(imgStream);
}
}
private static ImagePartType GetImagePartType(string imageFile)
{
string[] imgFileSplit = imageFile.Split('.');
string imgExtension = imgFileSplit.ElementAt(imgFileSplit.Count() - 1).ToString().ToLower();
if (imgExtension.Equals("jpg"))
imgExtension = "jpeg";
return (ImagePartType)Enum.Parse(typeof(ImagePartType), imgExtension, true);
}
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
}
}
Now here are my queries:
1.In the aspx page if i try to replace the templateFile with my own template(same as the sample)it gives me an error "Object reference not set to an instance of an object" at this line Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder") under AddTable.Otherwise it works fine.
2.Also in the second slide i am getting the required table but with the word "image" written 5 times on top of the page.
3.Also in the powerpoint file generated,the template style is not displayed on the slides except the first and the last slide(i.e the slides which are there in the template).
Thank you.
Related
Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}
Hi Guys, I'm building an app that has an Entry similar to that of tinder, does anyone have an idea on how I can achieve this. I tried creating multiple entries and move focus on the text entered but deleting is the issue as TextChaned method is only called when there is text
In Xamarin.Forms , you can Custom a Entry Render View in iOS to implement it .
Create a custom Entry :
public class CustomEntry : Entry
{
}
Then in Native iOS, create a CustomEntryRenderer :
public class CustomEntryRenderer : EntryRenderer
{
private UITextField textField;
int numberCount = 6;
nfloat itemMargin =20;
List<UILabel> labels = new List<UILabel>();
List<UIView> lines = new List<UIView>();
UIControl maskView = new UIControl();
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
textField = (UITextField)this.Control;
//textField.ReturnKeyType = UIReturnKeyType.Done;
textField.KeyboardType = UIKeyboardType.NumberPad;
textField.AutocapitalizationType = UITextAutocapitalizationType.None;
textField.TextColor = UIColor.Clear;
textField.TintColor = UIColor.Clear;
textField.EditingChanged += TextField_EditingChanged;
UIButton maskView = new UIButton();
maskView.BackgroundColor = UIColor.White;
maskView.TouchUpInside += MaskView_TouchUpInside;
textField.AddSubview(maskView);
this.maskView = maskView;
for (int i = 0; i < numberCount; i++)
{
UILabel label = new UILabel();
label.TextAlignment = UITextAlignment.Center;
label.TextColor = UIColor.DarkTextColor;
label.Font = UIFont.FromName("PingFangSC-Regular", 41);
textField.AddSubview(label);
labels.Add(label);
}
for(int i = 0; i < numberCount; i++)
{
UIView line = new UIView();
line.BackgroundColor = UIColor.Purple;
textField.AddSubview(line);
lines.Add(line);
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
nfloat temp = textField.Bounds.Size.Width - (itemMargin * (numberCount - 1));
nfloat w = temp / numberCount;
nfloat x = 0;
for(int i = 0; i < labels.Count; i++)
{
x = i * (w + itemMargin);
UILabel label = labels[i];
label.Frame = new CGRect(x, 0, w, textField.Bounds.Size.Height);
UIView line = lines[i];
line.Frame = new CGRect(x, textField.Bounds.Size.Height - 1, w, 1);
}
maskView.Frame = textField.Bounds;
}
private void MaskView_TouchUpInside(object sender, EventArgs e)
{
textField.BecomeFirstResponder();
}
private void TextField_EditingChanged(object sender, EventArgs e)
{
if(textField.Text.Length > numberCount)
{
//Range range = new Range(0, numberCount);
textField.Text = textField.Text.Substring(0, numberCount);
}
for(int i = 0; i < numberCount; i++)
{
UILabel label = labels[i];
if(i< textField.Text.Length)
{
label.Text = textField.Text.Substring(i, 1);
}
else
{
label.Text = "";
}
}
if (textField.Text.Length >= numberCount)
{
textField.ResignFirstResponder();
}
}
}
Finally , you can use it in Xaml :
<ProjectNameSpace:CustomEntry x:Name="customEntry" WidthRequest="300" />
The effect :
#region fillAllData4
private void fillAllData4()
{
clsCategory objCategory = new clsCategory(true);
clsProductMain objProduct = new clsProductMain(true);
objCategory.getDropDownMenu();
objProduct.getProduct();
string str = string.Empty;
int i = 0;
// int j = 0;
if (objCategory.ListclsCategory.Count > 0)
{
for (i = 0; i < objCategory.ListclsCategory.Count; i++)
{
cat.InnerHtml = objCategory.ListclsCategory[0].CategoryName;
cat1.InnerHtml = objCategory.ListclsCategory[1].CategoryName;
cat2.InnerHtml = objCategory.ListclsCategory[2].CategoryName;
cat3.InnerHtml = objCategory.ListclsCategory[3].CategoryName;
string[] filePaths = Directory.GetFiles(Server.MapPath("~/images/Saree/"));
int j = 0;
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
str += #"<div><div><img class='imges' src='images/Saree/" + fileName + #"' /></div>
<div class='sname'>" + objProduct.ListclsProductMain[j].ProductName + #"</div>
<div class='sname2'>" + objProduct.ListclsProductMain[j].MRP + #"</div></div>";
j++;
}
slider3.InnerHtml = str;
slider4.InnerHtml = str;
slider5.InnerHtml = str;
slider6.InnerHtml = str;
//System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
//new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
//createDiv.ID = "createDiv";
//createDiv.InnerHtml =str;
//this.Controls.Add(createDiv);
}
}
}
#endregion
Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
{
//'Continue shopping' URL
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.LastContinueShoppingPage,
_webHelper.GetThisPageUrl(false),
_storeContext.CurrentStore.Id);
if (model == null)
model = new SearchModel();
var searchTerms = model.q;
if (searchTerms == null)
searchTerms = "";
searchTerms = searchTerms.Trim();
//sorting
PrepareSortingOptions(model.PagingFilteringContext, command);
//view mode
PrepareViewModes(model.PagingFilteringContext, command);
//page size
PreparePageSizeOptions(model.PagingFilteringContext, command,
_catalogSettings.SearchPageAllowCustomersToSelectPageSize,
_catalogSettings.SearchPagePageSizeOptions,
_catalogSettings.SearchPageProductsPerPage);
string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
_workContext.WorkingLanguage.Id,
string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categories = _cacheManager.Get(cacheKey, () =>
{
var categoriesModel = new List<SearchModel.CategoryModel>();
//all categories
var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
foreach (var c in allCategories)
{
//generate full category name (breadcrumb)
string categoryBreadcrumb = "";
var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
for (int i = 0; i <= breadcrumb.Count - 1; i++)
{
categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
if (i != breadcrumb.Count - 1)
categoryBreadcrumb += " >> ";
}
categoriesModel.Add(new SearchModel.CategoryModel
{
Id = c.Id,
Breadcrumb = categoryBreadcrumb
});
}
return categoriesModel;
});
if (categories.Any())
{
//first empty entry
model.AvailableCategories.Add(new SelectListItem
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
//all other categories
foreach (var c in categories)
{
model.AvailableCategories.Add(new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Breadcrumb,
Selected = model.cid == c.Id
});
}
}
IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
if (Request.Params["q"] != null)
{
if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
{
model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
}
else
{
var categoryIds = new List<int>();
int manufacturerId = 0;
decimal? minPriceConverted = null;
decimal? maxPriceConverted = null;
bool searchInDescriptions = false;
int vendorId = 0;
if (model.adv)
{
//advanced search
var categoryId = model.cid;
if (categoryId > 0)
{
categoryIds.Add(categoryId);
if (model.isc)
{
//include subcategories
categoryIds.AddRange(GetChildCategoryIds(categoryId));
}
}
manufacturerId = model.mid;
//min price
if (!string.IsNullOrEmpty(model.pf))
{
decimal minPrice;
if (decimal.TryParse(model.pf, out minPrice))
minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
}
//max price
if (!string.IsNullOrEmpty(model.pt))
{
decimal maxPrice;
if (decimal.TryParse(model.pt, out maxPrice))
maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
}
if (model.asv)
vendorId = model.vid;
searchInDescriptions = model.sid;
}
//var searchInProductTags = false;
var searchInProductTags = searchInDescriptions;
//products
products = _productService.SearchProducts(
categoryIds: categoryIds,
manufacturerId: manufacturerId,
storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
priceMin: minPriceConverted,
priceMax: maxPriceConverted,
keywords: searchTerms,
//searchDescriptions: searchInDescriptions,
searchProductTags: searchInProductTags,
searchSku: true,
languageId: _workContext.WorkingLanguage.Id,
orderBy: (ProductSortingEnum)command.OrderBy,
pageIndex: command.PageNumber - 1,
pageSize: command.PageSize,
vendorId: vendorId);
model.Products = PrepareProductOverviewModels(products).ToList();
model.NoResults = !model.Products.Any();
//search term statistics
if (!String.IsNullOrEmpty(searchTerms))
{
var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
if (searchTerm != null)
{
searchTerm.Count++;
_searchTermService.UpdateSearchTerm(searchTerm);
}
else
{
searchTerm = new SearchTerm
{
Keyword = searchTerms,
StoreId = _storeContext.CurrentStore.Id,
Count = 1
};
_searchTermService.InsertSearchTerm(searchTerm);
}
}
//event
_eventPublisher.Publish(new ProductSearchEvent
{
SearchTerm = searchTerms,
SearchInDescriptions = searchInDescriptions,
CategoryIds = categoryIds,
ManufacturerId = manufacturerId,
WorkingLanguageId = _workContext.WorkingLanguage.Id,
VendorId = vendorId
});
}
}
model.PagingFilteringContext.LoadPagedList(products);
return View(model);
}
A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.
I was really hoping someone could help me,
I need to get the variable product from the method GridView1_RowDataBound to the quote value class string product.
Its for a pdf creator and any help would be greatly appreciated as i've been stuck on this for quite a while, please excuse as I'm fairly inexperienced in .net.
Thanks very much!!
enter code here
public partial class quotedetail : System.Web.UI.Page
{
private string quoteId;
private string product;
private string connectId = "";
string description = "Save Your Quote as a PDF with your Company Logo and Print out for Customers";
public string ConnectId { get { return connectId; } }
protected void Page_Init(object sender, EventArgs e)
{
connectId = Global.GetConnectionString();
quoteId = Request.QueryString["quote"];
product =
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
(Master as WebOnlineMasterPage).PageTitle = "Quote - " + quoteId;
DisplayPage();
}
}
protected void DisplayPage()
{
try
{
DataSet ds = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
FormView1.DataSource = ds.Tables[0];
GridView1.DataSource = ds.Tables[1];
Page.DataBind();
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Global.CheckException(ex);
description = "Sorry, information about this quote is unavailable.";
Panel1.Visible = false;
}
(Master as WebOnlineMasterPage).PageDescription = description;
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
protected void FormView1_DataBound(object sender, EventArgs e)
{
// get the expiry date
bool isopen = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["IsOpen"];
bool expired = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["Expired"];
int viewIndex = 0;
if (isopen && !expired)
viewIndex = 1;
// set appropriate view
MultiView view = (MultiView)FormView1.FindControl("QuoteProcessView");
view.ActiveViewIndex = viewIndex;
}
protected void AcceptQuote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("checkout.aspx?quote=" + quoteId);
}
protected void Requote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("requestquote.aspx?quote=" + quoteId);
}
// ********************PDF Start********************
protected void SaveAsPdf_Click(object sender, EventArgs e)
{
DataSet quote = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
Document document = CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = document;
renderer.RenderDocument();
MemoryStream ms = new MemoryStream();
renderer.PdfDocument.Save(ms);
byte[] pdfBytes = ms.ToArray();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=quote.pdf");
Response.AddHeader("Content-Length", pdfBytes.Length.ToString());
Response.BinaryWrite(pdfBytes);
Response.StatusCode = 200;
Response.End();
}
public Document CreateDocument()
{
Document document = new Document();
document.Info.Title = "A sample invoice";
document.Info.Subject = "Demonstrates how to create an invoice.";
DefineStyles(document);
TextFrame addressFrame;
MigraDoc.DocumentObjectModel.Tables.Table table;
CreatePage(document, out addressFrame, out table );
FillContent(document, addressFrame, table);
return document;
}
void DefineStyles(Document document)
{
// Get the predefined style Normal.
MigraDoc.DocumentObjectModel.Style style = document.Styles["Normal"];
// Because all styles are derived from Normal, the next line changes the
// font of the whole document. Or, more exactly, it changes the font of
// all styles and paragraphs that do not redefine the font.
style.Font.Name = "Verdana";
style = document.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Create a new style called Table based on style Normal
style = document.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Verdana";
style.Font.Name = "Times New Roman";
style.Font.Size = 9;
// Create a new style called Reference based on style Normal
style = document.Styles.AddStyle("Reference", "Normal");
style.ParagraphFormat.SpaceBefore = "5mm";
style.ParagraphFormat.SpaceAfter = "5mm";
style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
}
void CreatePage(Document document, out TextFrame addressFrame, out MigraDoc.DocumentObjectModel.Tables.Table table)
{
// Each MigraDoc document needs at least one section.
Section section = document.AddSection();
// Put a logo in the header
MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(Server.MapPath("~/images/cnwlogo.jpg"));
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
paragraph.AddText("PowerBooks Inc · Sample Street 42 · 56789 Cologne · Germany");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
addressFrame = section.AddTextFrame();
addressFrame.Height = "3.0cm";
addressFrame.Width = "7.0cm";
addressFrame.Left = ShapePosition.Left;
addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
addressFrame.Top = "5.0cm";
addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = addressFrame.AddParagraph("PowerBooks Inc · Sample Street 42 · 56789 Cologne");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("INVOICE", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Cologne, ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
table = section.AddTable();
table.Style = "Table";
table.Borders.Color = Colors.DarkBlue;
table.Borders.Width = 0.25;
table.Borders.Left.Width = 0.5;
table.Borders.Right.Width = 0.5;
table.Rows.LeftIndent = 0;
// Before you can add a row, you must define the columns
Column column = table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("5cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
CreateHeaderRow(table);
table.SetEdge(0, 0, 7, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, Color.Empty);
//create data table
}
private static void CreateHeaderRow(MigraDoc.DocumentObjectModel.Tables.Table table)
{
Row headerRow1 = table.AddRow();
headerRow1.HeadingFormat = true;
headerRow1.Format.Alignment = ParagraphAlignment.Center;
headerRow1.Format.Font.Bold = true;
headerRow1.Shading.Color = Colors.AliceBlue;
headerRow1.Cells[0].AddParagraph("PRODUCT");
headerRow1.Cells[0].Format.Font.Bold = false;
headerRow1.Cells[0].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[0].MergeDown = 1;
headerRow1.Cells[1].AddParagraph("DESCRIPTION");
headerRow1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[1].MergeDown = 1;
headerRow1.Cells[2].AddParagraph("QTY");
headerRow1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[2].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[2].MergeDown = 1;
headerRow1.Cells[3].AddParagraph("UNIT");
headerRow1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[3].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[3].MergeDown = 1;
headerRow1.Cells[4].AddParagraph("PRICE");
headerRow1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[4].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[4].MergeDown = 1;
headerRow1.Cells[5].AddParagraph("TAX");
headerRow1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[5].MergeDown = 1;
headerRow1.Cells[6].AddParagraph("TOTAL");
headerRow1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[6].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[6].MergeDown = 1;
}
class QuoteItemRow
{
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductID"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
public QuoteItemRow(decimal quantity, decimal price, decimal discount, string itemNumber, string title)
{
Quantity = quantity;
Price = price;
Discount = discount;
ItemNumber = itemNumber;
Title = title;
}
public decimal Quantity;
public decimal Discount;
public decimal Price;
public string ItemNumber;
public string Title;
}
void FillContent(Document document, TextFrame addressFrame, MigraDoc.DocumentObjectModel.Tables.Table table)
{
Paragraph paragraph = addressFrame.AddParagraph();
paragraph.AddText("Joe Bloggs");
paragraph.AddLineBreak();
paragraph.AddText("12 Some St");
paragraph.AddLineBreak();
paragraph.AddText(product);
// Iterate the invoice items
decimal totalExtendedPrice = 0;
QuoteItemRow[] items = new QuoteItemRow[] {
new QuoteItemRow (2.0m, 3.4m, 0.2m, "3213421", product ),
new QuoteItemRow (2.4m, 3.4m, 0.0m, "3534DD21", quoteId ),
new QuoteItemRow (8, 0.4m, 0.1m, "908587", quoteId ),
};
foreach (QuoteItemRow item in items)
{
decimal quantity = item.Quantity;
decimal price = item.Price;
decimal discount = item.Discount;
// Each item fills two rows
Row row1 = table.AddRow();
Row row2 = table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Colors.LightGray;
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
paragraph = row1.Cells[1].AddParagraph();
paragraph.AddFormattedText(item.Title, TextFormat.Bold);
row2.Cells[1].AddParagraph(item.Quantity.ToString());
row2.Cells[2].AddParagraph("$" + price.ToString("0.00"));
row2.Cells[3].AddParagraph("$" + discount.ToString("0.0"));
row2.Cells[4].AddParagraph();
row2.Cells[5].AddParagraph("$" + price.ToString("0.00"));
decimal extendedPrice = quantity * price;
extendedPrice = extendedPrice * (100 - discount) / 100;
row1.Cells[5].AddParagraph("$" + extendedPrice.ToString("0.00"));
row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
totalExtendedPrice += extendedPrice;
table.SetEdge(0, table.Rows.Count - 2, 6, 2, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
}
// Add an invisible row as a space line to the table
Row row = table.AddRow();
row.Borders.Visible = false;
// Add the total price row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Total Price");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Add the VAT row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("VAT (19%)");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph((0.19m * totalExtendedPrice).ToString("0.00") + " €");
// Add the additional fee row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Shipping and Handling");
row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
// Add the total due row
row = table.AddRow();
row.Cells[0].AddParagraph("Total Due");
row.Cells[0].Borders.Visible = false;
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
totalExtendedPrice += 0.19m * totalExtendedPrice;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Set the borders of the specified cell range
table.SetEdge(5, table.Rows.Count - 4, 1, 4, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
// Add the notes paragraph
paragraph = document.LastSection.AddParagraph();
paragraph.Format.SpaceBefore = "1cm";
paragraph.Format.Borders.Width = 0.75;
paragraph.Format.Borders.Distance = 3;
paragraph.Format.Borders.Color = Colors.DarkBlue;
paragraph.Format.Shading.Color = Colors.LightGray;
}
}
Easiest solution would be to put the value in a Session
Session.Add("ProductCode", ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
To get the value:
Session["ProductCode"].ToString()
Keep in mind though that you are doing this in the item databound, in the event that you are expecting multiple values for product code, I would suggest storing the values in a collection prior to putting it in the Session.
i.e.
if(Session["ProductCode"] != null)
{
List<string> pcodes = Session["ProductCode"] as List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
else
{
List<string> pcodes = new List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
To get the values:
Session["ProductCode"] as List<string>()