I am attempting to create a diagram using SoftArtisans' ExcelApplication, Anchor and Shape.
I am able to get shapes to appear on my output file; however, I have a requirement that the text shown in the Shape must read bottom to top, i.e. SHAPE must be shown as:
E
P
A
H
S
I am creating my shapes on the file using the following code, which exists in a for loop:
if (prevRow != null && prevRow.FixtureY != pogPicDtl.FixtureY)
{
currRow += 3;
currCol = 0;
}
double prodX = (double)pogPicDtl.PositionX;
double prodY = (double)pogPicDtl.PositionY;
Shapes sheetShapes = wb.Worksheets[sheetNumber].Shapes;
Anchor anchor = wb.Worksheets[sheetNumber].CreateAnchor(currRow, currCol, prodX * .1, prodY );
Shape box = sheetShapes.CreateShape(ShapeType.Rectangle, anchor);
box.FillColor = blue;
box.FillTransparency = 0.50;
box.Height =(double) pogPicDtl.PositionHeight *10;
box.Width = (double)pogPicDtl.PositionWidth*10;
// I want this Text to read upw
box.Text = Math.Round(pogPicDtl.PositionX,0).ToString() + "," + Math.Round(pogPicDtl.PositionY,0).ToString();
Is this possible with SoftArtisans? It is certainly possible when using Excel just on its own, but through the API, I have yet to find the text orientation to be modifiable when it is relating to a Shape.
According to http://wiki.softartisans.com/display/EW9/Shape this property is not currently supported. However ExcelWriter preserves most settings. Is it possible to have the shape with the text rotation already set in your input file, and just change the text.
Another option, depending on the shape, might be to just set shape rotation http://wiki.softartisans.com/display/EW9/Shape.Rotation so that the text appears to be read upwards.
Related
I want to identify the ColorSpace objects in PDF and fetch their location(coordinates, width and height of the colorspace) in the page. I tried traversing through the BaseDataObject in Contents.ContentContext.Resources.ColorSpaces, I can identify the Pantone Colorspaces in file (as shown in screenshot), but unable to find info regarding the location(x,y,w and h) of the object.
Where can I find the exact location of the visible objects(visible on opening a document) like ColorSpaces and embedded images?
I am using 'pdfclown' library to extract the info about ColorSpaces from PDF. Any inputs will be helpful. Thanks in advance.
ContentScanner cs = new ContentScanner(page);
System.Collections.Generic.List<org.pdfclown.documents.contents.colorSpaces.ColorSpace> list = cs.Contents.ContentContext.Resources.ColorSpaces.Values.ToList();
for (int i = 0; i < list.Count; i++)
{
org.pdfclown.objects.PdfArray array = (org.pdfclown.objects.PdfArray)list[i].BaseDataObject;
foreach (org.pdfclown.objects.PdfObject s in array)
{
//print colorspace and its x,y,w,h
}
}
PDF Document (has CMYK and Pantone Colors)
Screenshot
I want to identify the ColorSpace objects in PDF and fetch their location(coordinates, width and height of the colorspace) in the page.
I assume you mean the squares here:
Beware, these are not PDF ColorSpace objects, these are a number of simple (rectangular) paths filled with distinct colors and with some text drawn upon them.
PDF ColorSpaces are not specific renderings of colored areas, they are abstract color specifications:
Colours may be described in any of a variety of colour systems, or colour spaces. Some colour spaces are related to device colour representation (grayscale, RGB, CMYK), others to human visual perception (CIE-based). Certain special features are also modelled as colour spaces: patterns, colour mapping, separations, and high-fidelity and multitone colour.
(ISO 32000-1, section 8.6 "Colour Spaces")
As you look for something with coordinates, width and height, therefore, you are looking for drawing instructions using those abstract color spaces, not for the plain color spaces.
I tried traversing through the BaseDataObject in Contents.ContentContext.Resources.ColorSpaces, I can identify the Pantone Colorspaces in file (as shown in screenshot), but unable to find info regarding the location(x,y,w and h) of the object.
By looking at cs.Contents.ContentContext.Resources.ColorSpaces you get an enumeration of all special color spaces available for use in the current context but not the actual usages. To get the actual usages, you have to traverse the ContentScanner cs, i.e. you have to inspect the instructions in the current context, e.g. like this:
SeparationColorSpace space = null;
double X = 0, Y = 0, Width = 0, Height = 0;
void ScanForSpecialColorspaceUsage(ContentScanner cs)
{
cs.MoveFirst();
while (cs.MoveNext())
{
ContentObject content = cs.Current;
if (content is CompositeObject)
{
ScanForSpecialColorspaceUsage(cs.ChildLevel);
}
else if (content is SetFillColorSpace _cs)
{
ColorSpace _space = cs.Contents.ContentContext.Resources.ColorSpaces[_cs.Name];
space = _space as SeparationColorSpace;
}
else if (content is SetDeviceCMYKFillColor || content is SetDeviceGrayFillColor || content is SetDeviceRGBFillColor)
{
space = null;
}
else if (content is DrawRectangle _dr)
{
if (space != null)
{
X = _dr.X;
Y = _dr.Y;
Width = _dr.Width;
Height = _dr.Height;
}
}
else if (content is PaintPath _pp)
{
if (space != null && _pp.Filled && (X != 0 || Y != 0 || Width != 0 || Height != 0))
{
String name = ((PdfName)((PdfArray)space.BaseDataObject)[1]).ToString();
Console.WriteLine("Filling rectangle at {0}, {1} with size {2}x{3} using {4}", X, Y, Width, Height, name);
}
X = 0;
Y = 0;
Width = 0;
Height = 0;
}
}
}
BEWARE: This merely is a proof-of-concept, simplified as much as possible to still work in your PDF for the squares in the screen shot above.
For a general solution you will have to extend this considerably:
The code only inspects the given content scanner, i.e. only the content stream it has been initialized for, in your case a page content stream.
From such a context stream other content streams may be referenced, e.g. a form XObject. To catch all the usages of interesting color spaces in a generic document, you have to recursively inspect such dependent content streams, too.
The code ignores the current transformation matrix.
The current transformation matrix can be changed by an instruction to have all the drawings done by following instructions have their coordinates changed according to an affine transformation. To get all coordinates and dimensions right in a generic document, you have to apply the current transformation matrix to them.
The code ignores save-graphics-state/restore-graphics-state instructions.
The current graphics state (including fill color and current transformation matrix) can be stored on a stack and restored from it. To get colors, coordinates and dimensions right in a generic document, you have to keep track of saved and restored graphics states (or use data from the cs.State for color and transformation where PDF Clown does this for you).
The code only looks at Separation color spaces.
If you're interested in other color spaces, too, you have generalize this.
The code only understands very specific, trivial paths: only paths generated by a single instruction defining a rectangle.
For a generic solution you have to support arbitrary paths.
I added a new chart control (System.Windows.Forms.DataVisualiation.Charting) with ChartType Bar.
As requirement the label text must be white and into the bar value. Therefore I set the BarLabelStyle=Right in the CustomProperties of the DataPoint objects and the LabelForeColor to White.
See the below images.
The label in the 2nd gray bar is correctly shown.
The first bar instead is too small and the white text is shown out on the right side but is not visible.
However, when the bar is too short, the label text is positioned outside the bar and the text cannot be seen using white color.
Is there a way to check when the label text is drawn outside the bar value so that I can change the color (e.g. black)?
Thanks.
Unfortunately MCChart has almost no capacities wrt to dynamic expressions.
To work around you can either..:
Code the ForeColor depending on the y-value your DataPoints has. Either right when you add them or in a function that loops over all points, whenever you call it.. - Depending on the Font, the axis range and the label text this could be some threshold number you have to determine.
Example:
int p = yourSeries.Points.AddXY(...);
yourSeries.Points[p].LabelForeColor = yourSeries.Points[p].YValues[0] < threshold ?
Color.Black : Color.White;
Or you can cheat a little ;-)
You can set the LabelBackColor to have the same color as the Series, i.e. the bar itself. Here is is how to do that:
To access the Series.Color we have to call:
chart.ApplyPaletteColors();
Now we can set
yourSeries.LabelForeColor = Color.White;
yourSeries.LabelBackColor = yourSeries.Color;
Example:
Update:
Since you can't use the cheat you will have to set the colors.
The challenge is to know just how much space each label's text needs compared to how much space the bars have. The former can be measured (TextRenderer.MeasureString()) and the latter can be extracted from the y-axis (Axis.ValueToPixelPosition()).
Here is a function to do that; it is a little more complicated than I had hoped for, mostly because it tries to be generic..
void LabelColors(Chart chart, ChartArea ca, Series s)
{
if (chart.Series.Count <= 0 || chart.Series[0].Points.Count <= 0) return;
Axis ay = ca.AxisY;
// get the maximum & minimum values
double maxyv = ay.Maximum;
if (maxyv == double.NaN) maxyv = s.Points.Max(v => v.YValues[0]);
double minyv = s.Points.Min(v => v.YValues[0]);
// get the pixel positions of the minimum
int y0x = (int)ay.ValueToPixelPosition(0);
for (int i = 0; i < s.Points.Count; i++)
{
DataPoint dp = s.Points[i];
// pixel position of the bar right
int vx = (int)ay.ValueToPixelPosition(dp.YValues[0]);
// now we knowe the bar's width
int barWidth = vx - y0x;
// find out what the label text actauly is
string t = dp.LabelFormat != "" ?
String.Format(dp.LabelFormat, dp.YValues[0]) : dp.YValues[0].ToString();
string text = dp.Label != "" ? dp.Label : t;
// measure the (formatted) text
SizeF rect = TextRenderer.MeasureText(text, dp.Font);
Console.WriteLine(text);
dp.LabelForeColor = barWidth < rect.Width ? Color.Black : Color.White;
}
}
I may have overcomplicated the way to get at the text that should show; you certainly can decide if you can simplify for your case.
Note: You must call this function..
whenever your data may have changed
only after the axes of the chart have finished their layout (!)
The former point is obvious, the latter isn't. It means that you can't call the function right after adding your points! Instead you must do it at some later place or else the axis function needed to get the bar size will not work.
MSDN says it can only happen in a PaintXXX event; I found that all mouse events also work and then some..
To be save I'll put it in the PostPaint event:
private void chart_PostPaint(object sender, ChartPaintEventArgs e)
{
LabelColors(chart, chart.ChartAreas[0], chart.Series[0]);
}
i got a Little "Problem", i want to create a Chart looking like this:
So basically
Series 1 = Normal bar Chart. Color green if it Ends before the "time max" (series2) Series 2 = just a DataPoint / Marker on top of series 1 items.
I am struggling with this though...
my Code:
chart_TimeChart.Series.Clear();
string series_timeneeded = "Time Needed";
chart_TimeChart.Series.Add(series_timeneeded);
chart_TimeChart.Series[series_timeneeded]["PixelPointWidth"] = "5";
chart_TimeChart.ChartAreas[0].AxisY.ScrollBar.Size = 10;
chart_TimeChart.ChartAreas[0].AxisY.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
chart_TimeChart.ChartAreas[0].AxisY.ScrollBar.IsPositionedInside = true;
chart_TimeChart.ChartAreas[0].AxisY.ScrollBar.Enabled = true;
chart_TimeChart.Series[series_timeneeded].BorderWidth = 2;
chart_TimeChart.Series[series_timeneeded].ChartType = SeriesChartType.StackedBar;
chart_TimeChart.Series[series_timeneeded].YValueType = ChartValueType.Time;
chart_TimeChart.ChartAreas[0].AxisY.LabelStyle.Format = "HH:mm:ss";
chart_TimeChart.Series[series_timeneeded].XValueType = ChartValueType.String;
for (int i = 0; i < MaxNumber; i++)
{
chart_TimeChart.Series[series_timeneeded].Points.AddXY("item"+ " " + (i + 1).ToString(), DateTime.Now.Add(Timespans[i]));
}
chart_TimeChart.Series.Add(series_FinishTime);
chart_TimeChart.Series[series_FinishTime].ChartType = SeriesChartType.StackedBar;
chart_TimeChart.Series[series_FinishTime].BorderWidth = 0;
chart_TimeChart.Series[series_FinishTime].MarkerSize = 15;
chart_TimeChart.Series[series_FinishTime].MarkerStyle = MarkerStyle.Square;
chart_TimeChart.Series[series_FinishTime].MarkerColor = Color.Black;
chart_TimeChart.Series[series_FinishTime].YValueType = ChartValueType.DateTime;
chart_TimeChart.Series[series_FinishTime].XValueType = ChartValueType.String;
for (int i = 0; i < MaxNumber; i++)
{
DateTime YPosition = GetFinishTime(i);
chart_TimeChart.Series[series_FinishTime].Points.AddXY("item"+ " " +(i+1).ToString(), YPosition);
}
but this only Displays the 2nd series on top of the first one but the first one isnt visible anymore. The Maker of series 2 isnt shown but instead the bar is (eventhough i made borderwidth to 0). In my opinion/thinking i just have to make the "bar" of series 2 invisible and just Show the marker Points for series 2.
Any ideas?
Update:
string seriesname = Name+ i.ToString();
chart_TimeChart.Series.Add(seriesname);
chart_TimeChart.Series[seriesname].SetCustomProperty("DrawSideBySide", "false");
chart_TimeChart.Series[seriesname].SetCustomProperty("StackedGroupName", seriesname);
chart_TimeChart.Series[seriesname].ChartType = SeriesChartType.StackedBar; //Y and X are exchanged
chart_TimeChart.Series[seriesname].YValueType = ChartValueType.Time;
chart_TimeChart.ChartAreas[0].AxisY.LabelStyle.Format = "HH:mm:ss";
chart_TimeChart.Series[seriesname].XValueType = ChartValueType.String;
DateTime TimeNeeded = DateTime.Now.Add(List_AllLiniengroupsTimespans[k][i]);
DateTime TimeMax = GetFinishTime(k, i);
TimeSpan TimeDifference = TimeNeeded - TimeMax;
if (TimeNeeded > TimeMax) //All good
{
chart_TimeChart.Series[seriesname].Points.AddXY(seriesname, TimeNeeded); //Time till finish
chart_TimeChart.Series[seriesname].Points[0].Color = Color.Blue;
chart_TimeChart.Series[seriesname].Points[0].SetCustomProperty("StackedGroupName", seriesname);
chart_TimeChart.Series[seriesname].Points.AddXY(seriesname, TimeNeeded.Add(TimeDifference)); //time left
chart_TimeChart.Series[seriesname].Points[1].Color = Color.Red;
chart_TimeChart.Series[seriesname].Points[1].SetCustomProperty("StackedGroupName", seriesname);
}
else if (TimeMax > TimeNeeded) //wont make it in time
{
chart_TimeChart.Series[seriesname].Points.AddXY(seriesname, TimeNeeded); //time till still okay
chart_TimeChart.Series[seriesname].Points[0].Color = Color.Blue;
chart_TimeChart.Series[seriesname].Points[0].SetCustomProperty("StackedGroupName", seriesname);
chart_TimeChart.Series[seriesname].Points.AddXY(seriesname, TimeNeeded.Add(TimeDifference)); //Time that is too much
chart_TimeChart.Series[seriesname].Points[1].Color = Color.Green;
chart_TimeChart.Series[seriesname].Points[1].SetCustomProperty("StackedGroupName", seriesname);
}
else if (TimeMax == TimeNeeded) //fits exactly
{
chart_TimeChart.Series[seriesname].Points.AddXY(seriesname, TimeNeeded);
chart_TimeChart.Series[seriesname].Points[0].Color = Color.DarkOrange;
chart_TimeChart.Series[seriesname].Points[0].SetCustomProperty("StackedGroupName", seriesname);
}
the Code will be displayed as:
but i want it to look like this:
!! See the update below !!
If you really want to create a StackedBar chart, your chart has two issues:
If you want to stack datapoints they need to have meaningful x-values; without them how can it know what to stack on each other?
You add strings, which look fine but simply don't work. That is because the DataPoint.XValue field is double and when you add string into it it is set to 0 !! Your string is copied to the Label but otherwise lost.
So you need to come up with a suitable numeric value you use for the x-values..
And you also need to group the series you want to stack. For this there is a special property called StackedGroupName which serves to group those series that shall be stacked.
Here is how you can use it:
yourSeries1.SetCustomProperty("StackedGroupName", "Group1");
For a full example see this post !
It also shows one way of setting the Labels with string values of your choice..
This is the way to go for real StackedBar charts. Your workaround may or may not work. You could try to make the colors transparent or equal to the chart's backcolor; but it won't be more than a hack, imo.
Update
I guess I have misread the question. From what I see you do not really want to create a stacked chart.
Instead you struggle with these issues:
displaying bars at the same y-spot
making some bars invisible
displaying a vertical line as a marker
Let's tackle each:
Some column types including all Bars, Columns and then some have a little known special property called DrawSideBySide.
By default is is set to Auto, which will work like True. This is usually fine as we don't want bars to sit upon each other, effectively hiding all or part of the overlaid points.
But here we do want them to share the same y-position, so we need to set the property to false for at least one Series; the others (on Auto) will follow..:
You can do it either like this:
aSeries["DrawSideBySide"] = "false";
or like this:
aSeries.SetCustomProperty("DrawSideBySide", "false");
Next we hide the overlaid Series; this is simple:
aSeries.Color = Color.Transparent;
The last issue is displaying a line marker. There is no such MarkerStyle, so we need to use a custom style. For this we need to create a suitable bitmap and add it as a NamedImage to the chart's Images collection.
This sounds more complicated than it is; however the MarkerImage will not be scaled, so we need to created suitable sizes whenever we resize the Chart or add/remove points. I will ignore this complication for now..
int pointCount = 10;
Bitmap bmp = new Bitmap(2, chart.ClientSize.Height / pointCount - 5);
using (Graphics g = Graphics.FromImage(bmp)) g.Clear(Color.Black);
NamedImage marker = new NamedImage("marker", bmp);
chart.Images.Clear(); // quick & dirty
chart.Images.Add(marker);
Here is the result:
A few notes:
I would recommend to use variables for all chart elements you refer to repeatedly instead of using indexed references all the time. Less code, easier to read, a lot easier to maintain, and probably better performance.
Since your code called for the visible datapoints to be either red or green the Legend will not show a good representation. See here for an example of drawing a multi-colored legend item..
I used the chart height; this is not really recommended as there may be Titles or Legends or even more ChartAreas; instead you should use the height of the ChartArea, or even more precise, the height of the InnerPlotPosition. You would need to convert those from percentages to pixels. Not too hard, see below or see here
or here for more examples!
The markers should be adapted from the Resize and probably from the AxisViewChanged events. Putting it in a nice function to call (e.g. void setMarkerImage(Chart chart, Series s, string name, int width, Color c)) is always a good idea.
If you need to adapt the size of the marker image repeatedly, you may want to write better code for clearing the old one; this should include disposing of the Bitmap that was used before..
Here is an example:
var oldni = chart.Images.FindByName("marker");
if (oldni != null)
{
oldni.Image.Dispose();
chart.Images.Remove(oldni);
oldni.Dispose();
}
In some situations one needs to nudge the Chart to update some of its properties; RecalculateAxesScale is one such nudge.
Example for calculating a suitable marker height:
ChartArea ca = chart.ChartAreas[0];
ca.RecalculateAxesScale();
float cah = ca.Position.Height;
float iph = ca.InnerPlotPosition.Height;
float h = chart3.ClientSize.Height * cah / 100f * iph / 100f;
int mh = (int)(h / s.Points.Count);
Final note: The original answer stressed the importance of using meaningful x-values. Strings are useless! This was important for stacking bars; but it is equally important now, when we want bars to sit at the same vertical positions! Adding the x-values as strings is again resulting in nonsense..
(Since we have Bars the x-values go along the vertical axis and vice versa..)
Using VisualStudio WindowsForms Form. Creating Chart control in designer.
I'm trying to add some customLabels on charts Axis along WITH the default labels.
To do so I add customLabels with RowIndex property =1. Thus I see default labels AND my customLabels.
Now the problem is that while the default labels are rotated correctly my custom labels are not.
The Axis property LabelStyle.Angle affects only labels that are in RowIndex = 0, i.e. default labels.
And if I put customLabels at RowIndex=0 - all default labels will disappear.
What I see:
What I want to see:
I see no way to do that, really. The reason is probably that the developers decided there simply cannot be enough space for horizontal labels, once you start putting them in one or more extra rows..
Here is a workaround: Make those CustomLabels all transparent and draw them as you like in a xxxPaint event.
Here is an example:
I prepared the CustomLabels :
CustomLabel cl = new CustomLabel();
cl.ForeColor = Color.Transparent;
cl.RowIndex = 1;
...
And I code the drawing like this:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
Axis ay = chart1.ChartAreas[0].AxisY;
foreach (var cl in ay.CustomLabels)
{
if (cl.RowIndex == 1)
{
double vy = (cl.ToPosition + cl.FromPosition) / 2d;
int y = (int)ay.ValueToPixelPosition(vy);
e.ChartGraphics.Graphics.DrawString(cl.Text,
cl.Axis.TitleFont, Brushes.DarkRed, 0, y);
}
}
}
Do use a Font and Brush of your own liking. Here is the result:
Note that you may need to create more space to the left by tweaking the ChartArea.Position or the ChartArea.InnerPlotPosition, both of which are in 100% and, as usual, default to 'auto'.
For even more rows you need to change the check to cl.RowIndex < 0 and find a nice x position value for the DrawString.
My question is pretty straightforward, but I have a feeling the answer is a little more involved:
I'm trying to get the labels on this chart set up such that the first date will be to the left of the bar and the last date will be to the right:
Each bar is actually made of a point representing the whole timespan (drawn as a border with white inside color) and a point representing the % completed (drawn as the solid fill in those borders).
What I've got accomplished so far is done using Point CustomProperties:
Chart1.Series[s].Points[0].Label = gsvPhaseList[0].EndDate.Value.ToString("M/dd");
Chart1.Series[s].Points[0].SetCustomProperty("BarLabelStyle", "Outside");
Chart1.Series[s].Points[1].Label = gsvPhaseList[0].StartDate.Value.ToString("M/dd");
Chart1.Series[s].Points[1].SetCustomProperty("BarLabelStyle", "Left");
My problem is that there doesn't seem to be a way to say "Left & Outside".
My next step is to add a hook to the Paint event on the chart so I can actually get the label's position and shift to the left (I hope), but I wanted to make sure there wasn't something simple I'm missing first. Any ideas?
Your Chart displays RangeBars. You can fake the Outside-Left position by adding one extra DataPoint to the left of each Point.
You need to make it wide enough to hold the Label and you should keep it a little bit to the left of the real point, so the Label won't touch the side.
Make its Color = Color.Transparent and your Labels will show to the left and right.
Here is a piece of code that does the adornment for all Series in a Chart:
// just a few test data in Series S1 & S2..
S1.Points.AddXY(1, 13, 14.5); // the dummy point
S1.Points.AddXY(1, 15,22);
S2.Points.AddXY(1, 7,8.5); // 2nd dummy
S2.Points.AddXY(1, 9,13);
// set the labels
foreach (Series S in chart1.Series)
for (int i = 0; i < S.Points.Count; i+=2 )
{
DataPoint pt0 = S.Points[i];
DataPoint pt1 = S.Points[i + 1];
pt0.Color = Color.Transparent;
pt0.SetCustomProperty("BarLabelStyle", "Right");
pt0.Label = pt1.YValues[0] + " ";
pt1.SetCustomProperty("BarLabelStyle", "Outside");
pt1.Label = " " + pt1.YValues[1];
}
You could write code to actually add those extra label points automatically, too..