OpenXML Landscape on certain sections - c#

How do you set certain sections (what type of sections should I be using?) to landscape or portrait?
I am attempting to create sections that have the following section properties (see code below) and then set that section to landscape or portrait respectively. However, when I use this code and create break paragraphs the code generates a blank page in landscape.
public static SectionProperties PageOrientationPortrait()
{
SectionProperties sectionProperties2 = new SectionProperties();
PageSize pageSize = new PageSize()
{
Width = (UInt32Value)12240U,
Height = (UInt32Value)15840U,
Orient = PageOrientationValues.Portrait
};
PageMargin pageMargin = new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440U,
Bottom = 1440,
Left = (UInt32Value)1440U,
Header = (UInt32Value)720U,
Footer = (UInt32Value)720U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
sectionProperties2.Append(pageSize, pageMargin, columns, docGrid);
return sectionProperties2;
}
public static SectionProperties PageOrientationLandScape()
{
SectionProperties sectionProperties = new SectionProperties();
PageSize pageSize = new PageSize()
{
Width = (UInt32Value)15840U,
Height = (UInt32Value)12240U,
Orient = PageOrientationValues.Landscape
};
PageMargin pageMargin = new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440U,
Bottom = 1440,
Left = (UInt32Value)1440U,
Header = (UInt32Value)720U,
Footer = (UInt32Value)720U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
sectionProperties.Append(pageSize, pageMargin, columns, docGrid);
return sectionProperties;
}
public static Paragraph GenerateSectionBreakParagraph()
{
Paragraph paragraph232 = new Paragraph();
ParagraphProperties paragraphProperties220 = new ParagraphProperties();
SectionProperties sectionProperties1 = new SectionProperties();
SectionType sectionType1 = new SectionType() { Val = SectionMarkValues.NextPage };
sectionProperties1.Append(sectionType1);
paragraphProperties220.Append(sectionProperties1);
paragraph232.Append(paragraphProperties220);
return paragraph232;
}

When you wish to create a standard section in a WordProcessing document you first need to create an empty Paragraph element and an empty ParagraphProperties element. Then you can create a SectionProperties element with the desired properties as shown below:
/// <summary>
/// Will create a section properties
/// </summary>
/// <param name="orientation">The wanted orientation (landscape or portrai)</param>
/// <returns>A section properties element</returns>
public static SectionProperties CreateSectionProperties(PageOrientationValues orientation)
{
// create the section properties
SectionProperties properties = new SectionProperties();
// create the height and width
UInt32Value height = orientation == (PageOrientationValues.Portrait) ? 16839U : 11907U;
UInt32Value width = orientation != (PageOrientationValues.Portrait) ? 16839U : 11907U;
// create the page size and insert the wanted orientation
PageSize pageSize = new PageSize()
{
Width = width,
Height = height,
Code = (UInt16Value)9U,
// insert the orientation
Orient = orientation };
// create the page margin
PageMargin pageMargin = new PageMargin()
{
Top = 1417,
Right = (UInt32Value)1417U,
Bottom = 1417,
Left = (UInt32Value)1417U,
Header = (UInt32Value)708U,
Footer = (UInt32Value)708U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
// appen the page size and margin
properties.Append(pageSize, pageMargin, columns, docGrid);
return properties;
}
When creating a section properties element with a certain orientation it is important that you adjust the height and the width of the PageSize element accordingly. Otherwise the pages within the section will be rendered incorrectly (if you render a landscape section with portrait height and width the section will appear to be a portrait).
When we are done creating the sectionproperties all we need to do is to append the section properties to the empty paragraphproperties and then append the paragraphproperties to the paragraph.
Using this function we can create a word document having different orientated sections with the console program below:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace ChangeDocVariable
{
class Program
{
static void Main(string[] args)
{
using(WordprocessingDocument doc = WordprocessingDocument.Create(#"path to document", WordprocessingDocumentType.Document))
{
// Create the maindocument part
MainDocumentPart maindDocomentPart = doc.AddMainDocumentPart();
// add the document
Document document = maindDocomentPart.Document = new Document();
// add the bdoy
Body body = document.Body = new Body();
// insert a set of sections
// To insert a section we need to add a paragraph
// which contains paragaph properties
// which holds the section properties
Paragraph firstSection = new Paragraph();
ParagraphProperties firstSectionProperties = new ParagraphProperties();
firstSectionProperties.Append(CreateSectionProperties(PageOrientationValues.Portrait));
firstSection.Append(firstSectionProperties);
Paragraph secondSection = new Paragraph();
ParagraphProperties secondSectionProperties = new ParagraphProperties();
secondSectionProperties.Append(CreateSectionProperties(PageOrientationValues.Landscape));
secondSection.Append(secondSectionProperties);
Paragraph thirdSection = new Paragraph();
ParagraphProperties thirdSectionProperties = new ParagraphProperties();
thirdSectionProperties.Append(CreateSectionProperties(PageOrientationValues.Portrait));
thirdSection.Append(thirdSectionProperties);
body.Append(firstSection, secondSection, thirdSection);
// for the last section we can directly add a section properties
body.Append(CreateSectionProperties(PageOrientationValues.Landscape));
}
}
/// <summary>
/// Will create a section properties
/// </summary>
/// <param name="orientation">The wanted orientation (landscape or portrai)</param>
/// <returns>A section properties element</returns>
public static SectionProperties CreateSectionProperties(PageOrientationValues orientation)
{
// create the section properties
SectionProperties properties = new SectionProperties();
// create the height and width
UInt32Value height = orientation == (PageOrientationValues.Portrait) ? 16839U : 11907U;
UInt32Value width = orientation != (PageOrientationValues.Portrait) ? 16839U : 11907U;
// create the page size and insert the wanted orientation
PageSize pageSize = new PageSize()
{
Width = width,
Height = height,
Code = (UInt16Value)9U,
// insert the orientation
Orient = orientation };
// create the page margin
PageMargin pageMargin = new PageMargin()
{
Top = 1417,
Right = (UInt32Value)1417U,
Bottom = 1417,
Left = (UInt32Value)1417U,
Header = (UInt32Value)708U,
Footer = (UInt32Value)708U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
// appen the page size and margin
properties.Append(pageSize, pageMargin, columns, docGrid);
return properties;
}
}
}
This will create a document with four sections. The last SectionProrties can be directly added to the body of the document itself.

Related

Split overflow text in iText 7 paragraph

I have a document where the first page has three sections. The top and bottom section are required to be on the first page. The center section has dynamic text. I am trying to find a way to get all the text that will fit in the center section, set it, and then add the remaining to the continuation second page (if required).
I have looked at this S.O. answer, but it seems that it wouldn't allow for the bottom section to be placed where it needs to go.
Here is what I am trying to do.
using (var workStream = new MemoryStream())
{
using (var pdfWriter = new PdfWriter(workStream))
{
using (var pdfDoc = new PdfDocument(pdfWriter))
{
var document = new Document(pdfDoc);
var pageSize = pdfDoc.GetDefaultPageSize();
var width = pageSize.GetWidth() - document.GetLeftMargin() - document.GetRightMargin();
// *** First Top Section ***
// ... variable creations removed for brevity ...
document.Add(paragraph);
document.Add(table);
// *** CENTER SECTION ***
// This section has a required float height of 325f
// *** Third Bottom Section ***
// ... table creation removed for brevity ...
document.Add(table);
// *** Create the second page if needed and add the overflow text ***
}
}
}
I found a solution that works for me. I am sure I could streamline it, but tempest fugit.
So here is how I got the text for section 1:
// Set the height of section 2 paragraph
var section2Height = 325f;
// Create a Text element with the desired text
var tempText = new Text(myDesiredText).SetFont(font);
// Create rectangle for the allowable space for section 2
var rectangle = new Rectangle(width, section2Height);
// Create PDFCanvas for the document
var pdfCanvas = new PdfCanvas(pdfDoc, 1);
// Create canvas space for adding the temp paragraph to for splitting
var canvas = new Canvas(pdfCanvas, rectangle);
// Set the temp text to a paragraph
var synopsis = new Paragraph(tempText).SetFixedLeading(12f);
// Get the paragraph renderer
var renderer = synopsis.CreateRendererSubTree();
// Set the paragraph renderer parent to the canvas renderer
renderer.SetParent(canvas.GetRenderer());
// Process the renderer and get the layout result
var result = renderer.Layout(new LayoutContext(new LayoutArea(1, rectangle)));
// If the renderer is full, get all text, otherwise get the text that fits
var page1 = result.GetStatus() == LayoutResult.FULL ? renderer : result.GetSplitRenderer();
// Create a new paragraph for Section 2 (SYNOPSIS)
var newParagraph = new Paragraph().SetFixedLeading(12f);
// Set the Paragraph height and width
newParagraph.SetWidth(width);
newParagraph.SetHeight(section2Height);
// Get the count of child renderers. Each one is a new line
var page1Count = page1.GetChildRenderers().Count;
// Instantiate a string for the last renderer text
var lastText = string.Empty;
// Iterate through the child renderers
for (var i = 0; i < page1Count; i++)
{
// Get the string value
var text = page1.GetChildRenderers()[i].ToString();
// Create a text element
var t1 = new Text(text + Environment.NewLine).SetFont(font);
// Add the Text element to the new paragraph
newParagraph.Add(t1);
// If this is the last line, store the text for later use
if (i + 1 == page1Count)
lastText = text;
}
// Get the index of the last string of text
index = myDesiredText.IndexOf(lastText);
// Get the remaining text base off the index and the last text string length
var page2 = myDesiredText.Substring(index + lastText.Length);
// If there is a string value...
if (!string.IsNullOrEmpty(page2))
{
// Create a list of line returns
var returnCharList = new List<string> { "\r", "\n" };
// Remove the beginning line returns
while (returnCharList.Contains(page2.Substring(0, 1)))
page2 = page2.Substring(2);
}
// Add the new paragraph to the section
document.Add(newParagraph);
This I how I set the rest of the text to the next page
// If there is a second page, build it out
if (!string.IsNullOrEmpty(page2))
{
// Create the text element
var page2Text = new Text(page2).SetFont(font);
// Get the workable height for the paragraph minus the space for the page footer
var page2Height = height - 30f;
// Create page 2 paragraph
var page2Paragraph = new Paragraph(page2Text).SetHeight(page2Height).SetFixedLeading(12f);
// Add the paragraph to the document
document.Add(page2Paragraph);
// Create new pager
pager = new Paragraph().AddTabStops(tabStops);
// Set the page string for page 2
pageBill = $"EBM - { RemoveBillSpaces(bsd.Bill.BillNumber)} - 2 of { totalPages }";
// Create the text element
pagerText = new Text(pageBill).SetFont(font).SetFontSize(fontSize_Small);
// Add the tabs and text for the pager
pager
.Add(new Tab())
.Add(new Tab())
.Add(pagerText);
// Add the pager to page 2
document.Add(pager);
}

Stretched width for rotated UILabel

Sorry i'm really can't figure out how is native iOS design works (i'm usually do Xamarin Forms design).
I have UIStackView
UIStackView stackView = new UIStackView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height));
then i create UILabel, set AdjustsFontSizeToFitWidth = true because i need auto adjusted font size
after that i apply some rotation to it targetLabel.Transform = CGAffineTransform.MakeRotation(new nfloat(Math.PI * 270 / 180.0)); because i need to make vertical text.
and then i add this label to the stack. Of course i have some other setups too but i think they are doesn't matter.
my final step is to set new Frame for UILabel with fixed width. I tried set width by getting stack's height, i tried even set it to constant, but it doesn't work. Width of the label always looks like auto.
this is what i want:
but in fact, the target label is very small.
Full code here: (Note this is TodayExtension)
[Register("CodeBasedViewController")]
public class CodeBasedViewController : SLComposeServiceViewController, INCWidgetProviding
{
UIImage image;
private UILabel otherLabel;
private UILabel targetLabel;
public CodeBasedViewController(IntPtr handle) : base(handle)
{
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
UIStackView stackView = new UIStackView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height));
View.AddSubview(stackView);
stackView.Axis = UILayoutConstraintAxis.Horizontal;
image = new UIImage("picture.png");
UIImageView imageView = new UIImageView(image)
{
ContentMode = UIViewContentMode.ScaleAspectFit
};
otherLabel = new UILabel
{
TextColor = UIColor.White,
Text = "someTextA",
Font = UIFont.SystemFontOfSize(40)
};
targetLabel = new UILabel
{
TextColor = UIColor.Black,
Text ="4",
TextAlignment = UITextAlignment.Left,
Font = UIFont.SystemFontOfSize(30),
AdjustsFontSizeToFitWidth = true,
Lines = 1
};
targetLabel.Transform = CGAffineTransform.MakeRotation(new nfloat(Math.PI * 270 / 180.0));
stackView.AddArrangedSubview(imageView);
stackView.AddArrangedSubview(otherLabel);
stackView.AddArrangedSubview(targetLabel);
stackView.Frame = new CGRect(View.Frame.Width / 2, 0,
otherLabel .IntrinsicContentSize.Width +
targetLabel.IntrinsicContentSize.Width +
View.Frame.Height
, View.Frame.Height);
stackView.Center = View.Center;
targetLabel.Frame = new CGRect(targetLabel.Frame.X, targetLabel.Frame.Y, 150, 150); //test constants
}
public void WidgetPerformUpdate(Action<NCUpdateResult> completionHandler)
{
completionHandler(NCUpdateResult.NewData);
}
}
Firstly, set the property Distribution of StackView
stackView.Distribution = UIStackViewDistribution.Fill;
And don't forget to set the Font of label at the same time
targetLabel.Frame = new CGRect(targetLabel.Frame.X, targetLabel.Frame.Y, 150, 150);
targetLabel.Font = UIFont.SystemFontOfSize(80);
Following is the full code , I set the frame just for test and you can set the frame as you want(if you want to set the equals the size of screen , you should set the frame of label and imageView at same time).
UIStackView stackView = new UIStackView(new CGRect(100,200,300,150));
View.AddSubview(stackView);
stackView.Distribution = UIStackViewDistribution.Fill;
stackView.Spacing = 10;
stackView.BackgroundColor = UIColor.LightGray;
stackView.Axis = UILayoutConstraintAxis.Horizontal;
UIImageView imageView = new UIImageView()
{
ContentMode = UIViewContentMode.ScaleAspectFit,
BackgroundColor = UIColor.Red
};
otherLabel = new UILabel
{
TextColor = UIColor.Black,
Text = "someTextA",
Font = UIFont.SystemFontOfSize(40)
};
targetLabel = new UILabel
{
TextColor = UIColor.Black,
Text = "4",
TextAlignment = UITextAlignment.Left,
Font = UIFont.SystemFontOfSize(100),
AdjustsFontSizeToFitWidth = true,
Lines = 0
};
targetLabel.Transform = CGAffineTransform.MakeRotation(new nfloat(Math.PI * 270 / 180.0));
stackView.AddArrangedSubview(imageView);
stackView.AddArrangedSubview(otherLabel);
stackView.AddArrangedSubview(targetLabel);
stackView.Center = View.Center;
targetLabel.Frame = new CGRect(targetLabel.Frame.X, targetLabel.Frame.Y, 150, 150);

Aspose.Word page number in right margin

i build document with Aspose.Word. I try add page number in right margin. Image better explain it:
My result pdf preview
How to do it?
My current code:
var document = new Document();
_builder = new DocumentBuilder(document)
{
PageSetup =
{
Orientation = Orientation.Portrait,
PaperSize = PaperSize.A4,
RightMargin = ConvertUtil.MillimeterToPoint(20),
BottomMargin = ConvertUtil.MillimeterToPoint(35),
LeftMargin = ConvertUtil.MillimeterToPoint(35),
TopMargin = ConvertUtil.MillimeterToPoint(35)
}
};
_builder.StartTable();
_builder.InsertCell();
_builder.Write("Test test test");
_builder.EndTable();
_builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
_builder.Write("Pages: ");
_builder.InsertField("PAGE", "");
_builder.Write("/");
_builder.InsertField("NUMPAGES");
document.Save(stream, SaveFormat.Pdf);
In your case, you need to add text box in the footer of document, insert page number field in it, and set its position. Please use following modified code example to get the desired output.
var document = new Document();
DocumentBuilder _builder = new DocumentBuilder(document)
{
PageSetup =
{
Orientation = Orientation.Portrait,
PaperSize = Aspose.Words.PaperSize.A4,
RightMargin = ConvertUtil.MillimeterToPoint(20),
BottomMargin = ConvertUtil.MillimeterToPoint(35),
LeftMargin = ConvertUtil.MillimeterToPoint(35),
TopMargin = ConvertUtil.MillimeterToPoint(35)
}
};
_builder.StartTable();
_builder.InsertCell();
_builder.Write("Test test test");
_builder.EndTable();
_builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
Shape shape = new Shape(document, ShapeType.TextBox);
shape.Stroked = false;
shape.Width = _builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;
shape.Left = 0;
shape.Left = - _builder.CurrentSection.PageSetup.LeftMargin;
shape.Top = 0;
Paragraph paragraph = new Paragraph(document);
shape.AppendChild(paragraph);
_builder.InsertNode(shape);
_builder.MoveTo(paragraph);
_builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
_builder.Write("Pages: ");
_builder.InsertField("PAGE", "");
_builder.Write("/");
_builder.InsertField("NUMPAGES");
document.Save(MyDir + "output.pdf", SaveFormat.Pdf);
I work with Aspose as Developer evangelist.

Printing a stackpanel containing a listbox over multiple pages wpf

Hi I am looking to print a StackPanel that contains a listbox which can contain an infinite number of items and therefore needs to print over multiple pages. I found this code online and it works fine.
public static FixedDocument GetFixedDocument(FrameworkElement toPrint, PrintDialog printDialog)
{
if (printDialog == null)
{
printDialog = new PrintDialog();
}
var capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
var pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
var visibleSize = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
var fixedDoc = new FixedDocument();
//If the toPrint visual is not displayed on screen we neeed to measure and arrange it
toPrint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
toPrint.Arrange(new Rect(new Point(0, 0), toPrint.DesiredSize));
//
var size = toPrint.DesiredSize;
//Will assume for simplicity the control fits horizontally on the page
double yOffset = 0;
while (yOffset < size.Height)
{
var vb = new VisualBrush(toPrint)
{
Stretch = Stretch.None,
AlignmentX = AlignmentX.Left,
AlignmentY = AlignmentY.Top,
ViewboxUnits = BrushMappingMode.Absolute,
TileMode = TileMode.None,
Viewbox = new Rect(0, yOffset, visibleSize.Width, visibleSize.Height)
};
var pageContent = new PageContent();
var page = new FixedPage();
((IAddChild)pageContent).AddChild(page);
fixedDoc.Pages.Add(pageContent);
page.Width = pageSize.Width;
page.Height = pageSize.Height;
var canvas = new Canvas();
FixedPage.SetLeft(canvas, capabilities.PageImageableArea.OriginWidth);
FixedPage.SetTop(canvas, capabilities.PageImageableArea.OriginHeight);
canvas.Width = visibleSize.Width;
canvas.Height = visibleSize.Height;
canvas.Background = vb;
page.Children.Add(canvas);
yOffset += visibleSize.Height;
}
return fixedDoc;
}
However this causes certain items of a listbox to be cut off at the bottom of a page and continued on the next page (as shown below). Is it possible to modify this code in any way to determine the size of the page and if the current listboxitem does not fit onto this page that it starts on the next page? Quite new to all this so any help would be greatly appreciated.
I had a similiar task once and came up with this code, which uses a 'dummy' renderer to determine the height of the element up front and then either adds it to the current page or creates a new one. For sure, that's not a very beautiful solution, but it did the job at the time. Maybe you can take sth. away from it.
Size A4Size = new Size(793.92, 1122.24);
Size InfiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
var pages = new List<FrameworkElement>();
int pageNumber = 0;
var printDate = DateTime.Now;
var size = A4Size;
var currentPage = new Report(size, printDate);
currentPage.Render();
var listElements = new Queue<ElementsToPrint>(...);
var dummyRenderer = new Viewbox();
dummyRenderer.Child = currentPage;
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
var template = (DataTemplate)View.FindResource("ItemTemplate");
dummyRenderer.Child = null;
var availableHeight = currentPage.View.ActualHeight;
while (listElements.Count > 0)
{
var elementToRender = listElements.Dequeue();
dummyRenderer.Child = new ListViewItem()
{
Content = elementToRender,
ContentTemplate = template,
Foreground = Brushes.Black
};
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
var renderedItem = (ListViewItem)dummyRenderer.Child;
dummyRenderer.Child = null;
var willItFit = availableHeight > renderedItem.ActualHeight;
if (willItFit)
{
currentPage.DataListView.Items.Add(renderedItem);
availableHeight -= renderedItem.ActualHeight;
}
else
{
dummyRenderer.Child = currentPage;
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
dummyRenderer.Child = null;
pages.Add(currentPage);
// Set up a new Page
pageNumber++;
currentPage = new DiaryReport(size,pageNumber,printDate,anonymous);
dummyRenderer.Child = currentPage;
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
dummyRenderer.Child = null;
availableHeight = currentPage.DataListView.ActualHeight;
currentPage.DataListView.Items.Add(renderedItem);
availableHeight -= renderedItem.ActualHeight;
}

itextsharp table chart legends beneath bars

Can someone explain me how I can create chart like this one using itextsharp library.
As you can see here, this chart has attached table with legends to its bottom side. And each bar has year attached to it. I want to create something like that.
Second picture. This is what i have so far. I don't have year attached to each bar, and my legends are not beneath each bar like in top graph. If someone could guide me how to create identical graph like one on top i would be grateful. Thanks in advance!
How can I turn those labels to be displayed horizontally, and put those legends beneath years in table like one in picture number 1.
// Chart Centers By Year
var chartCentersByYear = new Chart
{
Width = 1000,
Height = 450,
RenderType = RenderType.ImageTag,
AntiAliasing = AntiAliasingStyles.Graphics,
TextAntiAliasingQuality = TextAntiAliasingQuality.High
};
chartCentersByYear.Titles.Add("Centers By Year");
chartCentersByYear.Titles[0].Font = new Font("Arial", 16f);
chartCentersByYear.Titles[0].Alignment = System.Drawing.ContentAlignment.TopLeft;
chartCentersByYear.ChartAreas.Add("");
chartCentersByYear.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
chartCentersByYear.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chartCentersByYear.Series.Add("Count");
chartCentersByYear.Series.Add("Cases");
chartCentersByYear.Series[0].ChartType = SeriesChartType.Column; //Pie
chartCentersByYear.Series[1].ChartType = SeriesChartType.StepLine; //StepLine
chartCentersByYear.Series[1].BorderDashStyle = ChartDashStyle.DashDot;
chartCentersByYear.Series[1].BorderWidth = 3;
chartCentersByYear.Series[0].Color = Color.Brown;
chartCentersByYear.Legends.Add("1");
chartCentersByYear.Legends.Add("2");
chartCentersByYear.Legends[0].HeaderSeparator = LegendSeparatorStyle.Line;
chartCentersByYear.Legends[0].HeaderSeparatorColor = Color.Black;
chartCentersByYear.Legends[0].ItemColumnSeparator = LegendSeparatorStyle.Line;
chartCentersByYear.Legends[0].ItemColumnSeparatorColor = Color.Black;
chartCentersByYear.Legends[1].HeaderSeparator = LegendSeparatorStyle.Line;
chartCentersByYear.Legends[1].HeaderSeparatorColor = Color.Black;
chartCentersByYear.Legends[1].ItemColumnSeparator = LegendSeparatorStyle.Line;
chartCentersByYear.Legends[1].ItemColumnSeparatorColor = Color.Black;
//For the Legend
LegendCellColumn firstColumn = new LegendCellColumn();
firstColumn.ColumnType = LegendCellColumnType.SeriesSymbol;
firstColumn.HeaderBackColor = Color.WhiteSmoke;
chartCentersByYear.Legends[0].CellColumns.Add(firstColumn);
chartCentersByYear.Legends[1].CellColumns.Add(firstColumn);
LegendCellColumn secondColumn = new LegendCellColumn();
secondColumn.ColumnType = LegendCellColumnType.Text;
secondColumn.Text = "#LEGENDTEXT";
secondColumn.HeaderBackColor = Color.WhiteSmoke;
LegendItem newItemCount = new LegendItem();
newItemCount.Cells.Add(LegendCellType.Text, "Count", System.Drawing.ContentAlignment.MiddleCenter);
newItemCount.BorderWidth = 1;
newItemCount.BorderDashStyle = ChartDashStyle.Solid;
LegendItem newItemCases = new LegendItem();
newItemCases.Cells.Add(LegendCellType.Text, "Cases", System.Drawing.ContentAlignment.MiddleCenter);
newItemCases.BorderWidth = 1;
newItemCases.BorderDashStyle = ChartDashStyle.Solid;
// Getting data from a stored procedure
var totalCentersByYearResult = new Repository().GetTotalCentersByYear();
foreach (IGD_spInternationalReportCenterWithTots1_Result item in totalCentersByYearResult)
{
// For Series
chartCentersByYear.Series[0].Points.AddXY(item.YearEcmo, item.Count);
chartCentersByYear.Series[1].Points.AddY(item.Cases);
// For Legend
newItemCount.Cells.Add(LegendCellType.Text, item.Count.ToString(), System.Drawing.ContentAlignment.MiddleCenter);
newItemCases.Cells.Add(LegendCellType.Text, item.Cases.ToString(), System.Drawing.ContentAlignment.MiddleCenter);
}
chartCentersByYear.Legends[0].CustomItems.Add(newItemCount);
chartCentersByYear.Legends[0].CustomItems.Add(newItemCases);
chartCentersByYear.Legends[0].Docking = Docking.Bottom;
chartCentersByYear.Legends[1].Docking = Docking.Bottom; //Top
chartCentersByYear.Series[0].YAxisType = AxisType.Primary;
chartCentersByYear.Series[1].YAxisType = AxisType.Secondary;
//For two coordinate systems
chartCentersByYear.ChartAreas[0].AxisY2.LineColor = Color.Transparent;
chartCentersByYear.ChartAreas[0].AxisY2.MajorGrid.Enabled = false;
chartCentersByYear.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
chartCentersByYear.ChartAreas[0].AxisY2.IsStartedFromZero = chartCentersByYear.ChartAreas[0].AxisY.IsStartedFromZero;
using (var chartimage = new MemoryStream())
{
chartCentersByYear.SaveImage(chartimage, ChartImageFormat.Png);
Byte[] newChart = chartimage.GetBuffer(); //return chartimage.GetBuffer();
var image = Image.GetInstance(newChart); //Image.GetInstance(Chart());
image.ScalePercent(50f);
image.SetAbsolutePosition(document.LeftMargin + 40, document.BottomMargin + 100);
document.Add(image);
}

Categories