First page is blackened after adding watermark - pdfsharp

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;
}

Related

EPPlus ColumnStacked chart data point colors

I am able to generate Column Stacked chart using EPPlus. There is is requirement to change the color of datapoint.
I found the solution of at enter link description here but it only changes the color of first datapoint of the series. Can I get help to change the color of other datapoints as well. Here is the concept that I am looking for enter image description here
Here is the function that helps to change datapoint first color
public void SetDataPointStyle(OfficeOpenXml.Drawing.Chart.ExcelChart chart, ExcelChartSerie series, int totalDataPoint, Color color)
{
var i = 0;
var found = false;
foreach (var s in chart.Series)
{
if (s == series)
{
found = true;
break;
}
++i;
}
if (!found) throw new InvalidOperationException("series not found.");
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "']]", nsm);
var doc = chart.ChartXml;
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa));
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
var valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));
valattrib.Value = ToHex(color).Substring(1);
//var ln = spPr.AppendChild(doc.CreateElement("a:ln", nsa));
//var lnSolidFill = ln.AppendChild(doc.CreateElement("a:solidFill", nsa));
//var lnSrgbClr = lnSolidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
//var lnValattrib = lnSrgbClr.Attributes.Append(doc.CreateAttribute("val"));
//lnValattrib.Value = ToHex(Color.Gray).Substring(1);
node.AppendChild(spPr);
}
public String ToHex(Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
SetDataPointStyle(chart, chart.Series[0], 1, Color.Tan);
You have to populate a series of data point colors per series. Here is an extension method that will set the series data points to random colors. Just have to specify the serie number. If pick your own colors just override the logic or send in an array to use:
public static void SetChartPointRandomColors(this ExcelChart chart, int serieNumber)
{
var chartXml = chart.ChartXml;
var nsa = chart.WorkSheet.Drawings.NameSpaceManager.LookupNamespace("a");
var nsuri = chartXml.DocumentElement.NamespaceURI;
var nsm = new XmlNamespaceManager(chartXml.NameTable);
nsm.AddNamespace("a", nsa);
nsm.AddNamespace("c", nsuri);
var serieNode = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + serieNumber + "']]", nsm);
var serie = chart.Series[serieNumber];
var points = serie.Series.Length;
var rand = new Random(serieNumber);
for (var i = 1; i <= points; i++)
{
var dPt = chartXml.CreateNode(XmlNodeType.Element, "dPt", nsuri);
var idx = chartXml.CreateNode(XmlNodeType.Element, "idx", nsuri);
var att = chartXml.CreateAttribute("val", nsuri);
att.Value = i.ToString();
idx.Attributes.Append(att);
dPt.AppendChild(idx);
var srgbClr = chartXml.CreateNode(XmlNodeType.Element, "srgbClr", nsa);
att = chartXml.CreateAttribute("val");
//Generate a random color - override with own logic to specify
var color = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
att.Value = $"{color.R:X2}{color.G:X2}{color.B:X2}";
srgbClr.Attributes.Append(att);
var solidFill = chartXml.CreateNode(XmlNodeType.Element, "solidFill", nsa);
solidFill.AppendChild(srgbClr);
var spPr = chartXml.CreateNode(XmlNodeType.Element, "spPr", nsuri);
spPr.AppendChild(solidFill);
dPt.AppendChild(spPr);
serieNode.AppendChild(dPt);
}
}
Here is an example of usage:
[TestMethod]
public void Chart_BarChart_Colors_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]{new DataColumn("Col1", typeof(int)),new DataColumn("Col2", typeof(int)),new DataColumn("Col3", typeof(int))});
for (var i = 0; i < 10; i++){var row = datatable.NewRow();row[0] = i;row[1] = i * 10;row[2] = i * 15;datatable.Rows.Add(row);}
//Create a test file
var fileInfo = new FileInfo(#"c:\temp\Chart_BarChart_Colors.xlsx");
if (fileInfo.Exists)
fileInfo.Delete();
using (var pck = new ExcelPackage(fileInfo))
{
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(datatable, true);
var chart = worksheet.Drawings.AddChart("chart test", eChartType.ColumnStacked);
chart.Series.Add(worksheet.Cells["B2:B11"], worksheet.Cells["A2:A11"]);
chart.Series.Add(worksheet.Cells["C2:C11"], worksheet.Cells["A2:A11"]);
chart.SetChartPointRandomColors(0);
chart.SetChartPointRandomColors(1);
pck.Save();
}
}
Will give you this:
I had a similar use case, I needed to set the color of a slice (datapoint) of a doughnut chart. This question/answer helped immensely and I figured I would share the result in case anyone else hits this issue.
Note 1: I am using C# 9 with nullability enabled; you can remove the !'s if you aren't using nullability.
Note 2: I have no use case for multiple series in a doughnut chart, so this is hardcoded to series 0. You can parameterize the SelectSingleNode index if this doesn't work for you.
public void SetDoughnutChartDataPointFill(ExcelChart chart, int dataPointIdx, Color color)
{
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:doughnutChart/c:ser[c:idx[#val='0']]", nsm)!;
var doc = chart.ChartXml;
var dPt = doc.CreateElement("c:dPt", nschart);
var cdpIdx = doc.CreateElement("c:idx", nschart);
var valattr = cdpIdx.Attributes!.Append(doc.CreateAttribute("val"));
valattr.Value = dataPointIdx.ToString();
dPt.AppendChild(cdpIdx);
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa))!;
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa))!;
var valattrib = srgbClr.Attributes!.Append(doc.CreateAttribute("val"));
valattrib.Value = string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
dPt.AppendChild(spPr);
node.AppendChild(dPt);
}

Google Sheets Google Analytics Data by Channel

I have a Google Sheets file which calls Google Analytics and pulls metrics. This works great. What I want to do is pull metrics by channel so that the far left column is a collection of channels (PPC, Display, Organic, Social, Email, Referral, Affiliate, Direct). Do I need to use the Multi-Channel Funnel setup? Or is there a better way to do this?
function getGAData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test Data");
// var startDate = dateToYMD(sheet.getRange(3,3).getValue());
// var endDate = dateToYMD(sheet.getRange(3,4).getValue());
var dateRanges = readDateRanges(sheet);
var profileIds = readProfileIds(sheet);
var GAMetrics = readGAMetrics(sheet);
var results = [];
var metrics = [];
var optArgs = [];
var filterCount = 0;
var prevFilter = '**NONE**';
var i, j, k;
var profileResults;
var tempResults;
for (i = 0; i < GAMetrics[0].length; i++) {
// Utilities.sleep(100);
if (prevFilter != GAMetrics[1][i]) {
metrics[filterCount] = GAMetrics[0][i];
optArgs[filterCount] = {
'start-index': '1',
'max-results': '10' // Display the first 250 results.
};
if (GAMetrics[1][i] != '')
optArgs[filterCount].filters = GAMetrics[1][i];
if (GAMetrics[2][i] != '')
optArgs[filterCount].segment = GAMetrics[2][i];
filterCount++;
} else {
metrics[filterCount-1] = metrics[filterCount-1] + ',' + GAMetrics[0][i];
}
prevFilter = GAMetrics[1][i];
}
for (i = 0; i < profileIds.length; i++) { // get GA data for each of the rows of input
profileResults = [];
var tableId = 'ga:' + profileIds[i][0];
var startDate = dateToYMD(dateRanges[i][0]);
var endDate = dateToYMD(dateRanges[i][1]);
for (j = 0; j < metrics.length; j++) {
var metric = metrics[j];
var options = optArgs[j];
//var options = {
// 'dimensions': 'ga:source',
//};
try {
// Make a request to the API.
tempResults = Analytics.Data.Ga.get(
'ga:' + profileIds[i][0], // Table id (format ga:xxxxxx).
dateToYMD(dateRanges[i][0]), // Start-date (format yyyy-MM-dd).
dateToYMD(dateRanges[i][1]), // End-date (format yyyy-MM-dd).
metrics[j], // Comma seperated list of metrics.
optArgs[j]);
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
if (typeof tempResults.getRows() != 'undefined')
appendArray(profileResults, tempResults.getRows()[0]);
} catch (e) {
Logger.log(e + ' - Profile ID: ' + profileIds[i][0] + ' - Metrics: ' + metrics[j] );
}
}
//append Profile results to the set
for (k = profileResults.length; k < GAMetrics[0].length; k++)
profileResults[k] = '0';
results.push(profileResults);
// Utilities.sleep(200);
}
sheet.getRange(6, 13, results.length, GAMetrics[0].length).setValues(results); // populate results on spreadsheet
emailLog('don#test.com','startDate');
}
function readDateRanges(sheet){
var rowStart = 6;
var columnStart = 1;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 2).getValues();
}
function readProfileIds(sheet) {
var rowStart = 6;
var columnStart = 3;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 1).getValues();
}
function readGAMetrics(sheet) {
var rowStart = 2;
var columnStart = 13;
var numColumns = sheet.getLastColumn() - columnStart + 1;
return sheet.getRange(rowStart, columnStart, 3, numColumns).getValues();
}
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
function appendArray(a1,a2) {
var startSize = a1.length;
for (var i = 0; i < a2.length; i++)
a1[startSize + i] = a2[i];
}
function emailLog(emailAddress,reportDate) {
var recipient = emailAddress; // Session.getActiveUser().getEmail();
var subject = 'GA Data Pull - extract for ' + reportDate;
var body = Logger.getLog();
MailApp.sendEmail(recipient, subject, body);
}

Paperjs inserting segments to a rectangle gives strange result

I am trying to add random segments along the path of a rectangle. Here is my jsfiddle http://jsfiddle.net/hhND7/1/
<canvas id='canvas' resize style='' style='padding:0; margin:0;'></canvas>
<script type="text/paperscript" canvas="canvas" >
var rect = new Path.Rectangle({x:200, y:100}, new Size(80, 100))
rect.strokeColor = 'gray'
rect.selected = true;
var pathCuts = rands(20, 0, 360).sort(function(a,b){return a - b});
var tArr = [];
for ( var i=0; i<pathCuts.length; i++){
var loc = rect.getLocationAt(pathCuts[i]);
tArr.push(loc.point);
var sE = new Path.Circle(loc.point, 2);
sE.strokeColor = 'red';
}
rect.insertSegments(1, tArr);
function rands(n, min, max) {
var range = max - min;
if (range < n)
throw new RangeError("Specified number range smaller than count requested");
function shuffle() {
var deck = [], p, t;
for (var i = 0; i < range; ++i)
deck[i] = i + min;
for (i = range - 1; i > 0; --i) {
p = Math.floor(Math.random() * i);
t = deck[i];
deck[i] = deck[p];
deck[p] = t;
}
return deck.slice(0, n);
}
function find() {
var used = {}, rv = [], r;
while (rv.length < n) {
r = Math.floor(Math.random() * range + min);
if (!used[r]) {
used[r] = true;
rv.push(r);
}
}
return rv;
}
return range < 3 * n ? shuffle() : find();
}
</script>
I think the problem is with the insertSegments function. But i can not find a solution.
If you want it to still look like the original polygon, you need to sort in the positions of the original segments. Since you can replace a path's segments with an array of curveLocation , you can just add the locations of these points to tArr, then sort by each element by it's offset:
var pathCuts = rands(20, 0, rect.length);
var tArr = [];
for ( var i=0; i<pathCuts.length; i++){
var loc = rect.getLocationAt(pathCuts[i]);
tArr.push(loc);
var sE = new Path.Circle(loc.point, 2);
sE.strokeColor = 'red';
}
for ( var i = 0, l = rect.segments.length; i < l; i++){
tArr.push(rect.segments[i].location);
}
tArr.sort(function(a,b){return a.offset - b.offset})
rect.segments = tArr;

Editing PresentationML using openxml

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.

datatype image in $.ajax

in page cap.aspx
==========================================================================
string code = GetRandomText();
Bitmap bitmap = new Bitmap(160,50,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
Pen pen = new Pen(Color.LavenderBlush);
Rectangle rect = new Rectangle(0,0,160,50);
SolidBrush b = new SolidBrush(Color.LightPink);
SolidBrush blue = new SolidBrush(Color.White);
int counter = 0;
g.DrawRectangle(pen, rect);
g.FillRectangle(b, rect);
for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
counter += 20;
}
DrawRandomLines(g);
bitmap.Save(Response.OutputStream,ImageFormat.Gif);
g.Dispose();
b.Dispose();
blue.Dispose();
bitmap.Dispose();
===================================================================================
<div id="DIVdialog" style="display:none">
<img src="cap.aspx"/>
</div>
===================================================================================
$("#DIVdialog").dialog();
==================================================================================
show dialog but does not show image? address cap.aspx is correct!
how get cap.aspx by $.ajax and datatype:image?
I think that the key here is to add the ContentType and the BufferOutput
context.Response.ContentType = "image/gif";
context.Response.BufferOutput = false;
Eg:
public void RenderIt(HttpContext context)
{
context.Response.ContentType = "image/gif";
context.Response.BufferOutput = false;
string code = GetRandomText();
using(Bitmap bitmap = new Bitmap(160,50,System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using(Graphics g = Graphics.FromImage(bitmap))
{
using(Pen pen = new Pen(Color.LavenderBlush)
{
using(SolidBrush b = new SolidBrush(Color.LightPink))
{
using(SolidBrush blue = new SolidBrush(Color.White))
{
Rectangle rect = new Rectangle(0,0,160,50);
int counter = 0;
g.DrawRectangle(pen, rect);
g.FillRectangle(b, rect);
for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
counter += 20;
}
DrawRandomLines(g);
g.Dispose();
b.Dispose();
blue.Dispose();
// Return
bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
// Dispose
bitmap.Dispose();
}
}
}
}
}
context.Response.End();
}

Resources