Add header and footer to XPS print output - wpf

XpsDocument is loaded from disk
Create a FixedDocumentSequence via XpsDocument.GetFixedDocumentSequence Method ()
Display the via a DocumentViewer
Would like to add to add header and footer to print
I don't need to add the header and footer back to the XPS document - only to the print output
I tried implementing DocumentPaginator but cannot get the sizing or placement to work
NOT the same as this footer to FlowDocument
I use the solution there for FlowDocuments just fine
Convert XAML Flow Document to XPS with Style
On the FixedDocumentSequence the sizing comes from document (I guess)
For example could mix landscape and portrait
I cannot figure out how to hook into the sizing and make room for a header and footer
I can stamp a header on it but it is over the top of the page
And landscape pages are cut off
Cannot assign a PageSize when it comes from a FixedDocumentSequence
As stated in the link it is a suggested pages size
DocumentPage.Size is read only
Even if I create DocumentPage of the Size I want when the page is loaded using DocumentPaginator.GetPage then the Size is overwritten
Even worse the DocumentPaginator does not seem to be properly aware of the Size as it does not deal with mixed landscape and portrait properly. Landscape is printed portrait and just runs off the page.
some one asked me to post code
there also might be a just plain better approach
see footer to FlowDocument for how to use it
this is where it breaks
// this gets the page size from GetPage - ignores size above
public class DocumentPaginatorWrapperXPS : DocumentPaginator
{
System.Windows.Size m_PageSize;
System.Windows.Size m_Margin;
DocumentPaginator m_Paginator;
FixedDocumentSequence fixedDocumentSequence;
Typeface m_Typeface;
private string printHeader;
private int? sID;
private string docID;
public DocumentPaginatorWrapperXPS(FixedDocumentSequence FixedDocumentSequence, System.Windows.Size margin, string PrintHeader, int? SID, string DOCID)
{
//m_PageSize = pageSize;
//m_PageSize = new Size(800, 600);
fixedDocumentSequence = FixedDocumentSequence;
m_Margin = margin;
m_Paginator = fixedDocumentSequence.DocumentPaginator;
//m_Paginator.PageSize = new System.Windows.Size(m_PageSize.Width - margin.Width * 2,
// //m_PageSize.Height - margin.Width * 2);
printHeader = PrintHeader;
sID = SID;
docID = DOCID;
}
Rect Move(Rect rect)
{
if (rect.IsEmpty)
{
return rect;
}
else
{
return new Rect(rect.Left + m_Margin.Width, rect.Top + m_Margin.Height,
rect.Width, rect.Height);
}
}
private Size sizeXPS;
public override DocumentPage GetPage(int pageNumber)
{
System.Windows.Documents.DocumentPage page = m_Paginator.GetPage(pageNumber);
Debug.WriteLine(page.Size.Width + " " + page.Size.Height);
m_Paginator.PageSize = new System.Windows.Size(page.Size.Width/2 - m_Margin.Width * 2, page.Size.Height/2 - m_Margin.Height * 2);
page = m_Paginator.GetPage(pageNumber); // this get the page size from GetPage - ignores size above
Debug.WriteLine(page.Size.Width + " " + page.Size.Height);
DynamicDocumentPaginator paginatorPage = fixedDocumentSequence.DocumentPaginator as DynamicDocumentPaginator;
paginatorPage.PageSize = new System.Windows.Size(page.Size.Width / 2 - m_Margin.Width * 2, page.Size.Height / 2 - m_Margin.Height * 2);
sizeXPS = new System.Windows.Size(page.Size.Width / 2 - m_Margin.Width * 2, page.Size.Height / 2 - m_Margin.Height * 2);
page = paginatorPage.GetPage(pageNumber); // still does not change the page size
Debug.WriteLine(page.Size.Width + " " + page.Size.Height);
//page.PageSize = new System.Windows.Size(m_PageSize.Width - margin.Width * 2,
//m_PageSize.Height - margin.Width * 2);
//page.Size = new System.Windows.Size(page.Size.Width - m_Margin.Width * 2, page.Size.Height - m_Margin.Height * 2);
//page.Size.Width = page.Size.Width - m_Margin.Width * 2;
// Create a wrapper visual for transformation and add extras
ContainerVisual newpage = new ContainerVisual();
DrawingVisual title = new DrawingVisual();
using (DrawingContext ctx = title.RenderOpen())
{
if (m_Typeface == null)
{
m_Typeface = new Typeface("Segoe UI Symbol"); //Ariel
}
//FormattedText text = new FormattedText("Attorney eyes only \uE18B \u1F440 Page " + (pageNumber + 1),
// System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
// m_Typeface, 14, System.Windows.Media.Brushes.Black);
string pageS = "m_PageSize.Width " + m_PageSize.Width + " m_Margin.Width " + m_Margin.Width + " m_PageSize.Height " + m_PageSize.Height + " m_Margin.Height " + m_Margin.Height + Environment.NewLine +
"page.Size.Width " + page.Size.Width + " page.Size.Height " + page.Size.Height;
FormattedText header = new FormattedText("\u1F440 " + printHeader + Environment.NewLine + pageS,
System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
m_Typeface, 14, System.Windows.Media.Brushes.Black);
ctx.DrawText(header, new System.Windows.Point(96 / 2, -96 / 4)); // 1/4 inch above page content
//text = new FormattedText(pageS, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
// m_Typeface, 14, System.Windows.Media.Brushes.Black);
string goGabe = string.Empty;
if (sID != null)
{
goGabe += Environment.NewLine + "Gabriel Docs™ sysDocID: " + sID;
if (!string.IsNullOrEmpty(docID))
goGabe += " docID: " + docID;
}
goGabe += Environment.NewLine + "Page: " + (pageNumber + 1) + " Date: " + DateTime.Now.ToString() + " User: " + App.StaticGabeLib.CurUserP.UserID;
FormattedText footer = new FormattedText(goGabe
, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
m_Typeface, 14, System.Windows.Media.Brushes.Black);
ctx.DrawText(footer, new System.Windows.Point(96 / 2, page.Size.Height - m_Margin.Height));
//ctx.DrawText(footer, new System.Windows.Point(96 / 2, m_Paginator.PageSize.Height - m_Margin.Height));
}
DrawingVisual background = new DrawingVisual();
using (DrawingContext ctx = background.RenderOpen())
{
ctx.DrawRectangle(new SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240)), null, page.ContentBox);
}
newpage.Children.Add(background); // Scale down page and center
ContainerVisual smallerPage = new ContainerVisual();
smallerPage.Children.Add(page.Visual);
smallerPage.Transform = new MatrixTransform(0.8, 0, 0, 0.8, 0.1 * page.ContentBox.Width, 0.1 * page.ContentBox.Height);
newpage.Children.Add(smallerPage);
newpage.Children.Add(title);
newpage.Transform = new TranslateTransform(m_Margin.Width, m_Margin.Height);
return new DocumentPage(newpage, m_PageSize, Move(page.BleedBox), Move(page.ContentBox));
}
public override bool IsPageCountValid
{
get
{
return m_Paginator.IsPageCountValid;
}
}
public override int PageCount
{
get
{
return m_Paginator.PageCount;
}
}
public override System.Windows.Size PageSize
{
get
{
Debug.WriteLine("PageSize " + sizeXPS.Width + " " + sizeXPS.Height);
return sizeXPS; // this is not called
//m_Paginator.PageSize;
}
set
{
sizeXPS = value;
// m_Paginator.PageSize = value;
}
}
public override IDocumentPaginatorSource Source
{
get
{
return m_Paginator.Source;
}
}
}

Related

How to stop other conditional formatting from disappearing when hackmodding databars into solid fills?

EPPlus has no support for extLst thing which is needed to make databars conditional formatting with solid fill. They are gradient by themselves without modifications.
I coded this to modify worksheet's xml directly (this gets databars from worksheet XML and then adds required extLst nodes):
public static Random Rnd = new Random();
public static string GenerateXlsId()
{
//{29BD882A-B741-482B-9067-72CC5D939236}
string id = string.Empty;
for (int i = 0; i < 32; i++)
if (Rnd.NextDouble() < 0.5)
id += Rnd.Next(0, 10);
else
id += (char)Rnd.Next(65, 91);
id = id.Insert(8, "-");
id = id.Insert(13, "-");
id = id.Insert(18, "-");
id = id.Insert(23, "-");
return id;
}
public static void FixDatabarsAtWorksheet(OfficeOpenXml.ExcelWorksheet eworksheet)
{
System.Xml.XmlNodeList databars = eworksheet.WorksheetXml.GetElementsByTagName("dataBar");
if (databars.Count > 0)
{
string conditional_formattings_str = string.Empty;
for (int i = 0; i < databars.Count; i++)
{
string temp_databar_id = GenerateXlsId();
databars[i].ParentNode.InnerXml += #"<extLst>
<ext uri=""{B025F937-C7B1-47D3-B67F-A62EFF666E3E}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:id>{" + temp_databar_id + #"}</x14:id>
</ext>
</extLst>";
//--
string temp_sqref = databars[i].ParentNode.ParentNode.Attributes["sqref"].Value;
string left_type = string.Empty;
string left_val = string.Empty;
string right_type = string.Empty;
string right_val = string.Empty;
string color = string.Empty;
Color databar_fill_color = Color.Empty;
Color databar_border_color = Color.Empty;
for (int j = 0; j < databars[i].ChildNodes.Count; j++)
if (databars[i].ChildNodes[j].LocalName == "cfvo" && databars[i].ChildNodes[j].Attributes["type"] != null)
{
if (string.IsNullOrEmpty(left_type))
left_type = databars[i].ChildNodes[j].Attributes["type"].Value;
else if (string.IsNullOrEmpty(right_type))
right_type = databars[i].ChildNodes[j].Attributes["type"].Value;
if (databars[i].ChildNodes[j].Attributes["val"] != null)
if (string.IsNullOrEmpty(left_val))
left_val = databars[i].ChildNodes[j].Attributes["val"].Value;
else if (string.IsNullOrEmpty(right_val))
right_val = databars[i].ChildNodes[j].Attributes["val"].Value;
}
else if (databars[i].ChildNodes[j].LocalName == "color")
{
color = databars[i].ChildNodes[j].Attributes["rgb"].Value;
int argb = Int32.Parse(color, System.Globalization.NumberStyles.HexNumber);
databar_fill_color = Color.FromArgb(argb);
databar_border_color = Color.FromArgb(255,
databar_fill_color.R - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.R - 50,
databar_fill_color.G - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.G - 50,
databar_fill_color.B - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.B - 50);
}
string temp_conditional_formatting_template = #"<x14:conditionalFormatting xmlns:xm=""http://schemas.microsoft.com/office/excel/2006/main"">
<x14:cfRule type=""dataBar"" id=""{" + temp_databar_id + #"}"">
<x14:dataBar minLength=""" + (string.IsNullOrEmpty(left_val) ? "0" : left_val) + "\" maxLength=\"" + (string.IsNullOrEmpty(right_val) ? "100" : right_val) + "\" gradient=\"0\" " + (databar_border_color.IsEmpty ? string.Empty : "border = \"1\"") + ">";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (left_type.ToLower() == "min" ? "autoMin" : left_type) + "\" />";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (right_type.ToLower() == "max" ? "autoMax" : right_type) + "\" />";
if (!databar_border_color.IsEmpty)
temp_conditional_formatting_template += Environment.NewLine + "<x14:borderColor rgb=\"" + BitConverter.ToString(new byte[] { databar_border_color.A, databar_border_color.R, databar_border_color.G, databar_border_color.B }).Replace("-", "") + "\" />";
temp_conditional_formatting_template += Environment.NewLine + #"</x14:dataBar>
</x14:cfRule>
<xm:sqref>" + temp_sqref + #"</xm:sqref>
</x14:conditionalFormatting>";
conditional_formattings_str += temp_conditional_formatting_template;
}
databars[0].ParentNode.ParentNode.ParentNode.InnerXml += #"<extLst>
<ext uri=""{78C0D931-6437-407d-A8EE-F0AAD7539E65}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:conditionalFormattings>" + conditional_formattings_str + #"
</x14:conditionalFormattings>
</ext>
</extLst>";
}
}
And this really makes databars solid fill, the problem is any other conditional formatting like GreaterThan loses it's style when true.
For example I add databar and GreaterThan 123 (green) conditional formattings.
Excel still see coditional formatting rule GreaterThan 123, but the style is not set when it's true (green is not set). While databars is displayed correctly at same time.
I don't know where to look... Someone help!
Thats the problem with hacks - they are so fragile! :)
I was able to get it work with another hack - setting the style differential formatting (dxf) reference which seems to be dropped when epplus saves. What might be happening is epplus only thinks there is one dxf on save so it doesnt set the value since excel will assume it is the first dxf style (index 0) but that is a bit of a guess.
Anyway, if you set the dxfid via XML manually it will find it. But order counts here, you have to apply the databar hack last otherwise it will hit the wrong reference:
[TestMethod]
public void FixDatabarsAtWorksheetTest()
{
//https://stackoverflow.com/questions/58417819/how-to-stop-other-conditional-formatting-from-disappearing-when-hackmodding-data
//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(object))
});
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
row[0] = i;
row[1] = i * 10;
row[2] = Path.GetRandomFileName();
datatable.Rows.Add(row);
}
//Create a test file
var fi = new FileInfo(#"c:\temp\FixDatabarsAtWorksheetTest.xlsx");
if (fi.Exists)
fi.Delete();
using (var pck = new ExcelPackage(fi))
{
var workbook = pck.Workbook;
var doc = workbook.Worksheets.Add("Sheet1");
doc.Cells.LoadFromDataTable(datatable, true);
//Set the greater than
var gtConditional = doc
.ConditionalFormatting
.AddGreaterThan(doc.Cells["A2:A11"]);
gtConditional.Formula = "2";
gtConditional.Style.Fill.BackgroundColor.Color = Color.GreenYellow;
//Fix the gt
var xdoc = doc.WorksheetXml;
var nsm = new XmlNamespaceManager(xdoc.NameTable);
nsm.AddNamespace("default", xdoc.DocumentElement.NamespaceURI);
var gtNode = xdoc.SelectSingleNode("/default:worksheet/default:conditionalFormatting[#sqref=\"A2:A11\"]", nsm);
//Create the new attribute for table
var att = xdoc.CreateAttribute("dxfId");
att.Value = "0";
gtNode
.FirstChild
.Attributes.Append(att);
//Set the bar condition LAST
var barConditional = doc
.ConditionalFormatting
.AddDatabar(doc.Cells["B2:B11"], Color.FromArgb(99, 195, 132));
barConditional.HighValue.Type = eExcelConditionalFormattingValueObjectType.Num;
barConditional.LowValue.Type = eExcelConditionalFormattingValueObjectType.Num;
barConditional.HighValue.Value = 82;
barConditional.LowValue.Value = 0;
FixDatabarsAtWorksheet(doc);
pck.Save();
}
}
I get this:
Not sure how feasible this is for you depending on how many conditional formats you have but its worth a shot.

Why does this image rendering benchmark crash on IOS but not in the simulator?

I tried to get a grasp of image rendering performance and created some code which draws full screen images using mutable images and PNGs.
The code runs fine in the simulator but on an iPhone SE it crashes after 50 seconds or short before a million images.
Is it a bug or is there another explanation since it doesn't crash in the simulator and I cannot see a memory leak in jvisualvm?
Here is the code:
public class FormMeasureImage extends Form implements Painter {
abstract class Wallpaper implements Painter {
private Component componentParent;
public Wallpaper(Component aComponentParent) {
componentParent = aComponentParent;
}
public void paint(Graphics aGraphics, Rectangle aRectangle) {
aGraphics.drawImage(
getImage(new Dimension(componentParent.getWidth(), componentParent.getHeight())),
0,
0);
}
public abstract Image getImage(Dimension aDimension);
}
class WallpaperTiledIcons extends Wallpaper {
private Image image;
private Dimension dimension;
public WallpaperTiledIcons(Component aComponentParent) {
super(aComponentParent);
}
public Image getImage(Dimension aDimension) {
if ((null == image || !dimension.equals(aDimension)) && null != aDimension) {
dimension = new Dimension(aDimension);
Label labelPattern = new Label("1234567890");
Style styleLabelPattern = labelPattern.getAllStyles();
styleLabelPattern.setBorder(Border.createEmpty());
styleLabelPattern.setMargin(0, 0, 0, 0);
// byte[] bytes = new byte[4];
// Arrays.fill(bytes, Style.UNIT_TYPE_PIXELS);
// styleLabelPattern.setPaddingUnit(bytes);
styleLabelPattern.setPadding(0, 0, 0, 1);
Dimension preferredSizeLabelPattern = labelPattern.getPreferredSize();
labelPattern.setSize(preferredSizeLabelPattern);
Image imagePattern = Image.createImage(
preferredSizeLabelPattern.getWidth(),
preferredSizeLabelPattern.getHeight(),
0x00000000);
Graphics graphicsImagePattern = imagePattern.getGraphics();
graphicsImagePattern.setAlpha(255);
labelPattern.paint(graphicsImagePattern);
image = Image.createImage(
aDimension.getWidth(),
aDimension.getHeight(),
0xff606060);
Graphics graphics = image.getGraphics();
if (graphics.isAntiAliasingSupported()) {
graphics.setAntiAliased(true);
}
int canvasWidth = preferredSizeLabelPattern.getWidth(), canvasHeight = preferredSizeLabelPattern.getHeight();
int[] clip = graphics.getClip();
Rectangle rectangleClip = new Rectangle(clip[0], clip[1], clip[2], clip[3]);
int columns = (rectangleClip.getX() + rectangleClip.getWidth()) / canvasWidth + 1;
int rows = (rectangleClip.getY() + rectangleClip.getHeight()) / canvasHeight + 1;
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
int x = canvasWidth * column;
int y = canvasHeight * row;
Rectangle rectangle = new Rectangle(x, y, canvasWidth, canvasHeight);
if (!rectangleClip.intersects(rectangle)) {
continue;
}
graphics.drawImage(imagePattern, x, y);
}
}
}
return image;
}
}
abstract class Stage {
long millisTotal;
long tally;
TextArea textArea;
public Stage(String aName) {
textArea = new TextArea();
textArea.setEditable(false);
getContentPane().add(textArea);
stages.add(this);
}
abstract void perform();
abstract boolean isPainted();
}
private Wallpaper wallpaper;
private List<Stage> stages = new ArrayList<>();
private Iterator<Stage> iteratorStages;
private Image imageEncoded;
public FormMeasureImage() {
super("FormMeasureImage", new BoxLayout(BoxLayout.Y_AXIS));
setScrollableX(false);
setScrollableY(true);
Style styleForm = getAllStyles();
styleForm.setBgTransparency(255);
styleForm.setBgPainter(this);
TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setText("Measuring image throughput.");
add(textArea);
}
#Override
public void paint(Graphics aGraphics, Rectangle aRectangle) {
if (null == iteratorStages) {
new Stage("create") {
void perform() {
long millisBefore = System.currentTimeMillis();
wallpaper = new WallpaperTiledIcons(FormMeasureImage.this);
wallpaper.getImage(aRectangle.getSize());
millisTotal += System.currentTimeMillis() - millisBefore;
tally++;
textArea.setText("create: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return false;
}
};
new Stage("mutable") {
void perform() {
long millisBefore = System.currentTimeMillis();
for (int index = 0; index < 1000; index++) {
wallpaper.paint(aGraphics, aRectangle);
tally++;
}
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("mutable: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return true;
}
};
new Stage("encoding") {
void perform() {
long millisBefore = System.currentTimeMillis();
try {
millisBefore = System.currentTimeMillis();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.getImageIO().save(wallpaper.getImage(null), byteArrayOutputStream, ImageIO.FORMAT_PNG, 1);
byteArrayOutputStream.close();
imageEncoded = Image.createImage(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
tally++;
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("encoding: " + millisTotal + " / " + tally);
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
millisTotal += System.currentTimeMillis() - millisBefore;
tally++;
textArea.setText("encoding: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return false;
}
};
new Stage("encoded") {
void perform() {
long millisBefore = System.currentTimeMillis();
for (int index = 0; index < 1000; index++) {
aGraphics.drawImage(
imageEncoded,
0,
0);
tally++;
}
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("encoded: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return true;
}
};
iteratorStages = stages.iterator();
}
while (!perform().isPainted()) {;}
}
private Stage perform() {
if (!iteratorStages.hasNext()) {
iteratorStages = stages.iterator();
}
Stage stage = iteratorStages.next();
stage.perform();
return stage;
}
}
It seems that the test case included an EDT violation of decoding off the EDT. This can work for some cases but because of the heavy usage it crashes.
Making UI code threadsafe is a difficult task which is doubly so cross platforms.

2D over 3D anti-aliasing artifacts

We have 3D models in WPF and use a cursor made from a Canvas and some internal parts. We turn the HW cursor off and move the Canvas through MouseEvent. The issue is that there are terrible artifacts on the screen as you move from left to right (not nearly as bad right to left). I have played with snaptodevicepixels, Edge mode and nvidea AA settings but the only thing that "fixes" is setting edge mode to aliased for the 3dviewport - and we don't want that. I have even made the cursor completely transparent and it still leaves artifacts.
I broke out some of the code for demonstration. You can especially see the artifacts moving upper-left to lower-right.
Anyone think they can help me out here? I'm head banging and not in a good way. It's looking more like a bug in the AA code.
Thanks
T
FYI: I used some Petzold code here for the beach ball.
Bad AA BeachBall
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
namespace Cursoraa2
{
class Program : Window
{
[STAThread]
public static void Main() => new Application().Run(new Program());
public Program()
{
Width = 500;
Height = 500;
var grid = new Grid();
var viewport = new Viewport3D();
grid.Children.Add(viewport);
Content = grid;
//RenderOptions.SetEdgeMode(viewport,EdgeMode.Aliased);
DynamicCurosr.Start(grid, grid, 40, Color.FromArgb(40, 0x33, 0x33, 0xff), Colors.Blue);
MouseMove += MainWindow_MouseMove;
MakeBeachBallSphere(viewport);
}
private void MainWindow_MouseMove(object sender, MouseEventArgs e) => DynamicCurosr.Move(e.GetPosition(this));
public void MakeBeachBallSphere(Viewport3D viewport)
{
// Get the MeshGeometry3D from the GenerateSphere method.
var mesh = GenerateSphere(new Point3D(0, 0, 0), 1, 36, 18);
mesh.Freeze();
// Define a brush for the sphere.
var brushes = new Brush[6] { Brushes.Red, Brushes.Blue,
Brushes.Yellow, Brushes.Orange,
Brushes.White, Brushes.Green };
var drawgrp = new DrawingGroup();
for (var i = 0; i < brushes.Length; i++)
{
var rectgeo = new RectangleGeometry(new Rect(10 * i, 0, 10, 60));
var geodraw = new GeometryDrawing(brushes[i], null, rectgeo);
drawgrp.Children.Add(geodraw);
}
var drawbrsh = new DrawingBrush(drawgrp);
drawbrsh.Freeze();
// Define the GeometryModel3D.
var geomod = new GeometryModel3D
{
Geometry = mesh,
Material = new DiffuseMaterial(drawbrsh)
};
// Create a ModelVisual3D for the GeometryModel3D.
var modvis = new ModelVisual3D { Content = geomod };
viewport.Children.Add(modvis);
// Create another ModelVisual3D for light.
var modgrp = new Model3DGroup();
modgrp.Children.Add(new AmbientLight(Color.FromRgb(128, 128, 128)));
modgrp.Children.Add(new DirectionalLight(Color.FromRgb(128, 128, 128), new Vector3D(2, -3, -1)));
modvis = new ModelVisual3D {Content = modgrp};
viewport.Children.Add(modvis);
// Create the camera.
var cam = new PerspectiveCamera(new Point3D(0, 0, 8), new Vector3D(0, 0, -1), new Vector3D(0, 1, 0), 45);
viewport.Camera = cam;
// Create a transform for the GeometryModel3D.
var axisangle = new AxisAngleRotation3D(new Vector3D(1, 1, 0), 180);
var rotate = new RotateTransform3D(axisangle);
geomod.Transform = rotate;
// Animate the RotateTransform3D.
//DoubleAnimation anima = new DoubleAnimation(360, new Duration(TimeSpan.FromSeconds(5)));
//anima.RepeatBehavior = RepeatBehavior.Forever;
//axisangle.BeginAnimation(AxisAngleRotation3D.AngleProperty, anima);
}
MeshGeometry3D GenerateSphere(Point3D center, double radius, int slices, int stacks)
{
// Create the MeshGeometry3D.
var mesh = new MeshGeometry3D();
// Fill the Position, Normals, and TextureCoordinates collections.
for (var stack = 0; stack <= stacks; stack++)
{
var phi = Math.PI / 2 - stack * Math.PI / stacks;
var y = radius * Math.Sin(phi);
var scale = -radius * Math.Cos(phi);
for (var slice = 0; slice <= slices; slice++)
{
var theta = slice * 2 * Math.PI / slices;
var x = scale * Math.Sin(theta);
var z = scale * Math.Cos(theta);
var normal = new Vector3D(x, y, z);
mesh.Normals.Add(normal);
mesh.Positions.Add(normal + center);
mesh.TextureCoordinates.Add(
new Point((double)slice / slices,
(double)stack / stacks));
}
}
// Fill the TriangleIndices collection.
for (var stack = 0; stack < stacks; stack++)
for (var slice = 0; slice < slices; slice++)
{
var n = slices + 1; // Keep the line length down.
if (stack != 0)
{
mesh.TriangleIndices.Add((stack + 0) * n + slice);
mesh.TriangleIndices.Add((stack + 1) * n + slice);
mesh.TriangleIndices.Add((stack + 0) * n + slice + 1);
}
if (stack != stacks - 1)
{
mesh.TriangleIndices.Add((stack + 0) * n + slice + 1);
mesh.TriangleIndices.Add((stack + 1) * n + slice);
mesh.TriangleIndices.Add((stack + 1) * n + slice + 1);
}
}
return mesh;
}
}
public static class DynamicCurosr
{
static public bool InSession { get; private set; }
private static Panel theCursor;
private static readonly ScaleTransform ScaleTransform = new ScaleTransform(1, 1);
private static readonly MatrixTransform MatrixTransform = new MatrixTransform(1, 0, 0, 1, 0, 0);
private static Color defaultFill = Color.FromArgb(20, 255, 255, 255);
private static Color fillFromUser;
private static double strokeFromUser = 0;
private static Color strokeColorFromUser = Colors.Black;
private static int centerDotSizeFromUser = 10; // need to get from user
private static double initialDiameter = double.NaN;
private static Panel cursorPanel;
private static Panel mousePanel;
public static bool Start(Panel cursorPanelIn, Panel mousePanelIn, double radius)
{
return Start(cursorPanelIn, mousePanelIn, radius, defaultFill);
}
public static bool Start(Panel cursorPanelIn, Panel mousePanelIn, double radius, Color fill, Color strokeColor = default(Color), double strokeSize = .16)
{
strokeColor = strokeColor == default(Color) ? Colors.Black : strokeColor;
strokeColorFromUser = strokeColor;
fillFromUser = fill;
strokeFromUser = strokeColor == default(Color) ? 0 : strokeSize;
initialDiameter = double.IsNaN(initialDiameter) ? radius * 2 : initialDiameter;
return Start(cursorPanelIn, mousePanelIn);
}
private static bool Start(Panel cursorPanelIn, Panel mousePanelIn)
{
if (InSession) return false;
cursorPanel = cursorPanelIn;
mousePanel = mousePanelIn;
var point = Mouse.GetPosition(cursorPanel);
theCursor = MakeACursor(theCursor, initialDiameter / 2);
InSession = true;
cursorPanel.Cursor = Cursors.None;
theCursor.Visibility = Visibility.Visible;
Move(point);
if (cursorPanel.Children.Contains(theCursor))
return false;
cursorPanel.Children.Add(theCursor);
Mouse.OverrideCursor = Cursors.None;
return true;
}
public static void Stop()
{
if (InSession)
{
Mouse.OverrideCursor = null;
theCursor.Visibility = Visibility.Collapsed;
cursorPanel.Children.Remove(theCursor);
InSession = false;
}
}
public static void Move(Point point)
{
if (InSession && theCursor.Visibility == Visibility.Visible)
{
var m = MatrixTransform.Matrix;
m.OffsetX = point.X - theCursor.Width / 2;
m.OffsetY = point.Y - theCursor.Height / 2;
MatrixTransform.Matrix = m;
theCursor.RenderTransform = MatrixTransform;
}
}
public static Panel MakeACursor(Panel theCursor, double radius, Color fillColorIn = default(Color), Color strokeColorIn = default(Color))
{
var strokeColor = new SolidColorBrush(strokeColorIn == default(Color) ? strokeColorFromUser : strokeColorIn);
if (theCursor == null)
{
theCursor = new Grid()
{
Width = radius * 2,
Height = radius * 2,
Background = null,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
RenderTransform = ScaleTransform,
RenderTransformOrigin = new Point(.5, .5),
};
var cursorElement = new Ellipse
{
Width = radius * 2,
Height = radius * 2,
Fill = new SolidColorBrush(fillColorIn == default(Color) ? fillFromUser : fillColorIn),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
StrokeThickness = strokeFromUser,
Stroke = strokeColor,
RenderTransformOrigin = new Point(.5, .5)
};
theCursor.Children.Add(cursorElement);
}
MakeCursorOverlay(theCursor, radius, strokeColor);
return theCursor;
}
public static void MakeCursorOverlay(Panel theCursor, double radius, SolidColorBrush strokeColor)
{
var save = theCursor.Children[0];
theCursor.Children.Clear();
theCursor.Children.Add(save);
var circle = new Ellipse
{
Width = centerDotSizeFromUser,
Height = centerDotSizeFromUser,
Fill = null,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
StrokeThickness = strokeFromUser,
Stroke = strokeColor,
RenderTransformOrigin = new Point(.5, .5)
};
theCursor.Children.Add(circle);
}
}
}

C# Windows Application Image Resizing Before Saving

I have this Code to Save a Pic to my Solution Explorer Images Folder.
private void btnUploadImage_Click(object sender, EventArgs e)
{
//The String used to store the location of the file that is currently loaded in the picture box picFile
String location;
//The String used to store the name of the file that is currently loaded in the picture box picFile
String fileName;
ofdImageUpload.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
//Showing the fileopen dialog box
ofdImageUpload.ShowDialog();
//showing the image opened in the picturebox
imgCapture.Image = new Bitmap(ofdImageUpload.FileName);
//storing the location of the pic in variable
location = ofdImageUpload.FileName;
txtImgLocation.Text = location;
//storing the filename of the pic in variable
fileName = ofdImageUpload.SafeFileName;
//pictureboxImage.Image.Save();
imgCapture.SizeMode = PictureBoxSizeMode.StretchImage;
if (imgCapture.Image != null)
{
lblHiddenMsg.Text = "";
}
}
private void InsertGatepassEntry(int RowId)
{
string ContName = txtContName.Text.Trim();
string ContAdd = richtxtContAddress.Text.Trim();
string VisitorName = txtEmpName.Text.Trim();
string VisitorAdd = txtEmpAddress.Text.Trim();
string VisitorFathersName = txtEmpFatherName.Text.Trim();
string VisitorAge = txtEmpAge.Text.Trim();
string VisitorEsi = txtEsi.Text.Trim();
string VisitorContact = txtEmpContactNo.Text.Trim();
string VisitorBloodGrp = comboxBloodGroup.SelectedText.Trim();
string VisitorIssueDate = dtpEmpDateOfIssue.Text.Trim();
string imagename = ofdImageUpload.SafeFileName;
if (imagename != null || imagename != "") //Check If image is Selected from Computer's Hard Drive
{
if (imgCapture.Image != null)
{
//string imagepath = ofdImageUpload.FileName;
//string picname = imagepath.Substring(imagepath.LastIndexOf('\\'));
string picname = imagename;
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
Bitmap imgImage = new Bitmap(imgCapture.Image); //Create an object of Bitmap class/
//string fullPathName = path + "Images" + picname;
imgImage.Save(path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg");
string Image = "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg";
string GatepassNo = LoadLastGatepassNo();
switch (Contractor.InsertGatepassEntry(RowId, ContName, ContAdd, VisitorName, VisitorAdd, VisitorFathersName, VisitorAge, VisitorEsi, VisitorContact, VisitorBloodGrp, VisitorIssueDate, Image, GatepassNo))
{
case ProjectCreateStatus.Insertrow:
lblMessage.Text = "Information inserted successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblGatepassNo.Text = GatepassNo;
break;
}
}
else
{
lblHiddenMsg.Visible = true;
lblHiddenMsg.Text = "Please capture or browse an image First";
}
}
else //image is directly uploding from Webcam Capture
{
string Image = lblHiddenMsg.Text;
string GatepassNo = LoadLastGatepassNo();
switch (Contractor.InsertGatepassEntry(RowId, ContName, ContAdd, VisitorName, VisitorAdd, VisitorFathersName, VisitorAge, VisitorEsi, VisitorContact, VisitorBloodGrp, VisitorIssueDate, Image, GatepassNo))
{
case ProjectCreateStatus.Insertrow:
lblMessage.Text = "Information inserted successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblGatepassNo.Text = GatepassNo;
break;
}
}
}
private void bntCapture_Click(object sender, EventArgs e)
{
imgCapture.Image = imgVideo.Image;
Bitmap b = new Bitmap(imgCapture.Image);
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
b.Save(path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg");
lblHiddenMsg.Text = path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg";
}
Now I want to Save those uploaded Pic to my Images Folder to a particular Size like 250x250. can Anyone Help ? m new in Windows Application C#.
To resize your image use:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(250,250));
hi you can add the "Size" class as a parameter of your Bitmap constructor to resize the image
i did for you this function to make it easy hope that will help you
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(250,250));

Batch file to compare two different files having different data

I want to compare both files, if data is not matched, then print a message "DATA is not the same" and, if they match successfully, print "DATA is the same".
Content of First File (Live.txt):
Last
4000
5000
(2 Row affected)
Content Second File(Sup.txt) :
Last
3000
6000
(2 Row affected)
OS: Windows7
On Microsoft Windows you can use fc command.
On Linux and similar systems
cmp <file1> <file2>
will tell you if the files are different and:
diff <file1> <file2>
will show the differences.
we can also write large files byte by byte with a particular layout and fill the differences in the excel
import java.awt.image.SampleModel;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class FlatFileComparator {
/*
* Get the three flat files.
*
* One for Layout, Second for Expected File Third for Actual file
*/
public static void main(String args[]) throws Exception {
String fileName = "recordLayout.txt";
String actualFileName = "Actual.txt";
String expectedFileName = "Expected.txt";
List<String> recordLayout = null;
FlatFileComparator fb = new FlatFileComparator();
recordLayout = fb.getFileLayout(fileName);
fb.compareExpectedActual(actualFileName, expectedFileName, recordLayout);
}
// Get the Record Names of the Layout and put it in the List with the Field
// Name, Start Index and End Index
public List<String> getFileLayout(String layoutFileName) throws Exception {
List<String> fileLayoutList = new ArrayList<String>();
File layoutFile = new File(layoutFileName);
FileInputStream layoutFileInputStream = new FileInputStream(layoutFile);
BufferedReader layoutBuffReader = new BufferedReader(
new InputStreamReader(layoutFileInputStream));
String currentLine;
try {
while ((currentLine = layoutBuffReader.readLine()) != null) {
if ((currentLine.trim().equals(""))) {
throw new Exception(
"There should not be any empty lines in the middle of the Layout File");
}
String fieldName = currentLine.substring(0,
currentLine.indexOf(":"));
String startIndex = currentLine.substring(
currentLine.indexOf(":") + 2, currentLine.indexOf(","));
String endIndex = currentLine.substring(
currentLine.indexOf(",") + 1,
currentLine.lastIndexOf(")"));
fileLayoutList.add(fieldName);
fileLayoutList.add(startIndex);
fileLayoutList.add(endIndex);
// System.out.println(fieldName);
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Exception(
"You have not provided the Layout File for processing. Please provide it and try again");
}
return fileLayoutList;
}
// Get the Actual and Expected File and compare according to the position
public void compareExpectedActual(String actualFileName,
String expectedFileName, List<String> fileLayoutList)
throws Exception {
File actualFile = new File(actualFileName);
File expectedFile = new File(expectedFileName);
FileInputStream actualFileInputStream = new FileInputStream(actualFile);
BufferedReader actBuffReader = new BufferedReader(
new InputStreamReader(actualFileInputStream));
FileInputStream expectedFileInputStream = new FileInputStream(
expectedFile);
BufferedReader expBuffReader = new BufferedReader(
new InputStreamReader(expectedFileInputStream));
HSSFWorkbook excelWorkbook = new HSSFWorkbook();
HSSFSheet excelSheet = excelWorkbook.createSheet("File Comparator");
HSSFRow headerExcelRow = excelSheet.createRow(1);
HSSFRow currExcelRow = null;
HSSFCell headerExcelCell = null;
HSSFCell currExcelCell = null;
headerExcelCell = headerExcelRow.createCell(1);
headerExcelCell.setCellValue("Field Name");
for (int fieldName = 2, listNum = 0; listNum < fileLayoutList.size(); fieldName++) {
currExcelRow = excelSheet.createRow(fieldName);
currExcelCell = currExcelRow.createCell(1);
// System.out.println(listNum);
currExcelCell.setCellValue(fileLayoutList.get(listNum));
listNum += 3;
}
System.out.println(fileLayoutList.size());
int excelNum = 2;
for (String actualFileCurrLine, expectedFileCurrLine; (actualFileCurrLine = actBuffReader
.readLine()) != null
&& (expectedFileCurrLine = expBuffReader.readLine()) != null; excelNum += 4) {
char[] actualArray = actualFileCurrLine.toCharArray();
char[] expectedArray = expectedFileCurrLine.toCharArray();
for (int i = 0, excelRow = 2; i < fileLayoutList.size(); i += 3, excelRow++) {
boolean resultOfCompare = false;
String expectedString = "";
String actualString = "";
for (int j = Integer.parseInt(fileLayoutList.get(i + 1)); j <= Integer
.parseInt(fileLayoutList.get(i + 2)); j++) {
expectedString += expectedArray[j - 1];
// System.out.println("Array Index"+j);
System.out.println(fileLayoutList.get(i + 1));
System.out.println(fileLayoutList.get(i + 2));
actualString += actualArray[j - 1];
}
if (expectedString.equals(actualString))
resultOfCompare = true;
System.out.println(expectedString + "-" + actualString);
System.out.println("Row Number" + excelRow);
headerExcelCell = headerExcelRow.createCell(excelNum);
headerExcelCell.setCellValue("Actual");
headerExcelCell = headerExcelRow.createCell(excelNum + 1);
headerExcelCell.setCellValue("Expected");
headerExcelCell = headerExcelRow.createCell(excelNum + 2);
headerExcelCell.setCellValue("Result");
System.out.println("Cell Value" + "[" + excelRow + ","
+ excelNum + "]=" + actualString);
currExcelRow = excelSheet.getRow(excelRow);
currExcelCell = currExcelRow.createCell(excelNum);
currExcelCell.setCellValue(actualString);
System.out.println("Cell Value" + "[" + excelRow + ","
+ (excelNum + 1) + "]=" + actualString);
currExcelCell = currExcelRow.createCell(excelNum + 1);
currExcelCell.setCellValue(expectedString);
System.out.println("Cell Value" + "[" + excelRow + ","
+ (excelNum + 2) + "]=" + resultOfCompare);
currExcelCell = currExcelRow.createCell(excelNum + 2);
currExcelCell.setCellValue(resultOfCompare);
}
}
FileOutputStream s = new FileOutputStream("FlatfileComparator.xls");
excelWorkbook.write(s);
}
}

Resources