how to generate PDF from .aspx page - c#

i want to create PDF, from a currently running .aspx page and i successfully done this. But problem is that when i login through a login page and go for to create a PDF of a report_page(i can access this report_page only when i successfully login) and click on button to generate a PDF of currently running report_page then here PDF is generating of a login page rather than report_page.
And here i have another report_page which need not to login to generate report when i am generating report through this report_page(not need to login) and try to convert it to PDF then it is working correctly means here PDF is generated of report_page.
here i paste my code please check it and give me solution for this:
protected void btn_print_Click(object sender, EventArgs e)
{
try
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
int width = 850;
int height = 550;
Thumbnail1 thumbnail = new Thumbnail1(url, 990, 1000, width, height);
Bitmap image = thumbnail.GenerateThumbnail();
image.Save(Server.MapPath("~") + "/Dwnld/Thumbnail.bmp");
imagepath = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.bmp";
imagepath1 = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.pdf";
convetToPdf();
}
catch (Exception)
{
throw;
}
}
string imagepath = null;
string imagepath1 = null;
public void convetToPdf()
{
PdfDocument doc = new PdfDocument();
System.Drawing.Size size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
PdfPage pdfPage = new PdfPage();
pdfPage.Orientation = PageOrientation.Landscape;
doc.Pages.Add(pdfPage);
// XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4)
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(imagepath);
xgr.DrawImage(img, 0, 0);
doc.Save(imagepath1);
xgr.Dispose();
img.Dispose();
doc.Close();
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = imagepath1;
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
}
public class Thumbnail1
{
public string Url { get; set; }
public Bitmap ThumbnailImage { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int BrowserWidth { get; set; }
public int BrowserHeight { get; set; }
public Thumbnail1(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.Url = Url;
this.BrowserWidth = BrowserWidth;
this.BrowserHeight = BrowserHeight;
this.Height = ThumbnailHeight;
this.Width = ThumbnailWidth;
}
public Bitmap GenerateThumbnail()
{
Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return ThumbnailImage;
}
private void GenerateThumbnailInteral()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(this.Url);
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents();
webBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser webBrowser = (WebBrowser)sender;
webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
}
}
protected void CreateThumbnailImage(object sender, EventArgs e)
{
}

The issue is that you are requesting the page-to-be-generated in a separate request which does not include your login cookie/session. It is requesting it as though it was a completely separate browser would.
The only way I can think is that if you have basic authentication turned on in IIS you can change the url to be: http://myThumbnailUser:myThumbnailPassw0rd#www.mydomain.com/path/to/page/to/be/rendered.aspx.
You could try and attach the method that does all the generation to the page unload event to allow you to get the response stream, pump it into the WebBrowser control and thenuse that to generate your PDF.
protected void btn_print_Click(object sender, EventArgs e)
{
try
{
int width = 850;
int height = 550;
this.Page.Unload += delegate {
Thumbnail1 thumbnail = new Thumbnail1(this.Page, 990, 1000, width, height);
Bitmap image = thumbnail.GenerateThumbnail();
image.Save(Server.MapPath("~") + "/Dwnld/Thumbnail.bmp");
imagepath = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.bmp";
imagepath1 = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.pdf";
convetToPdf();
}
}
catch (Exception)
{
throw;
}
}
...
public Thumbnail1(Page page, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.Page = page;
this.BrowserWidth = BrowserWidth;
this.BrowserHeight = BrowserHeight;
this.Height = ThumbnailHeight;
this.Width = ThumbnailWidth;
}
...
private void GenerateThumbnailInteral()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(this.Url);
webBrowser.DocumentStream = this.Page.Response.GetResponseStream()
webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
}
That also might work..

Related

image doesn't change - WPF

I'm trying to change an image on runtime but it's not working.
I have a user control that when you click on imagebtn it's opening a new window with a list of images.
the next step is to take the image selected from the list, close the new window, and put the image on the imagebtn.
the user control still opens in the background.
this is my code.
NewWindow:
private string myData;
public ImagesWindow()
{
InitializeComponent();
InitialImageList();
}
private async void InitialImageList()
{
//add try catch
string get = await HttpRequests.GetRequest(URLImages);
allJsonCategory = JsonConvert.DeserializeObject<List<ImageArray>>(get);
Console.WriteLine(get);
ImageBoxList.ItemsSource = images;
foreach (var item in allJsonCategory)
{
images.Add(item);
}
}
private void ImageBoxList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedImage = (ImageArray)ImageBoxList.SelectedItem;
myData = selectedImage.full_path;
Console.WriteLine("you clicked on: " + selectedImage.name);
ProductsCategory pro = new ProductsCategory();
pro.imagePath = myData;
this.Close();
}
my usercontrol(in mainWindow):
public void setImage(string imagePath)
{
if (!imageURL.Equals(""))
{
Image imageBtn = new Image();
var imgUrl = new Uri(imagePath);
var imageData = new WebClient().DownloadData(imgUrl);
// or you can download it Async won't block your UI
// var imageData = await new WebClient().DownloadDataTaskAsync(imgUrl);
var bitmapImage = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad };
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(imageData);
bitmapImage.EndInit();
imageBtn.Source = bitmapImage;
//this.imageBtn.InvalidateVisual();
}
}
XAML of the image:
where is my mistake?
thank you all :)

How to display 2 images at same time in winform

In winforms I have two picture box one for portrait and other for Landscape.
Do to the size of the file or some reasons they are not downloading at same time,
let say if portrait image downloaded first,Now I click the updated button it was showing portrait image,
after second image downloaded when I click the update button it was showing Landscape image only.
I need both images should show, after downloading both images, but in my case it showing only one image(the latest downloaded image).
what should I do, Here is the code.
private void DisplayLogos(LogoHeader imageHeader)
{
if (imageHeader.carId == 2)
{
PortraitLabel.Text = "Portrait Image";
PortraitLabel.Visible = true;
MemoryStream ms = new MemoryStream(imageHeader.Images.First());
Image image = Image.FromStream(ms);
Bitmap bmp = new Bitmap(image);
PortraitPictureBox.Image = image;
PortraitPictureBox.Visible = true;
}
else if (imageHeader.carId == 1)
{
LandscapeLabel.Text = "Landscape Image ";
LandscapeLabel.Visible = true;
MemoryStream ms = new MemoryStream(imageHeader.Images.First());
LandscapePictureBox.Image = Image.FromStream(ms);
LandscapePictureBox.Visible = true;
}
}
public class LogoHeader
{
public LogoHeader(Access au, int Id)
{
carId = Id;
}
public int carId { get; set; }
public byte[] image{ get; set; }
public List<byte[]> Images
{
get
{
List<byte[]> logos = new List<byte[]>();
logos.Add(image);
return logos;
}
}
}
In order to keep the image you can't close (or change) the stream, you can simply create another one.
private void DisplayLogos(LogoHeader imageHeader)
{
if (imageHeader.carId == 2)
{
PortraitLabel.Text = "Portrait Image";
PortraitLabel.Visible = true;
MemoryStream ms1 = new MemoryStream(imageHeader.Images.First());
Image image = Image.FromStream(ms1);
Bitmap bmp = new Bitmap(image);
PortraitPictureBox.Image = image;
PortraitPictureBox.Visible = true;
}
else if (imageHeader.carId == 1)
{
LandscapeLabel.Text = "Landscape Image ";
LandscapeLabel.Visible = true;
MemoryStream ms2 = new MemoryStream(imageHeader.Images.First());
LandscapePictureBox.Image = Image.FromStream(ms2);
LandscapePictureBox.Visible = true;
}
}

Microsoft Cognitive Face API- how can i get Face Attributes in video feed from Kinect?

I'm exploring Microsoft Cognitive Face API and I'm very new to it. I'm able to achieve Face Attributes with an image which is easy but, my question is how can I get Face Attributes of a person in a real time video feed from Kinect in WPF c#. It would be great if somebody can help me out. Thanks in Advance!
I have tried capturing the frame from the Kinect color feed at every 2 seconds to some file location and use that file path and converted it to a Stream and then pass it on to the Face-API Functions and that worked. Following is the code I tried.
namespace CognitiveFaceAPISample
{
public partial class MainWindow : Window
{
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("c2446f84b1eb486ca11e2f5d6e670878");
KinectSensor ks;
ColorFrameReader cfr;
byte[] colorData;
ColorImageFormat format;
WriteableBitmap wbmp;
BitmapSource bmpSource;
int imageSerial;
DispatcherTimer timer,timer2;
string streamF = "Frames//frame.jpg";
public MainWindow()
{
InitializeComponent();
ks = KinectSensor.GetDefault();
ks.Open();
var fd = ks.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
uint frameSize = fd.BytesPerPixel * fd.LengthInPixels;
colorData = new byte[frameSize];
format = ColorImageFormat.Bgra;
imageSerial = 0;
cfr = ks.ColorFrameSource.OpenReader();
cfr.FrameArrived += cfr_FrameArrived;
}
void cfr_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
if (e.FrameReference == null) return;
using (ColorFrame cf = e.FrameReference.AcquireFrame())
{
if (cf == null) return;
cf.CopyConvertedFrameDataToArray(colorData, format);
var fd = cf.FrameDescription;
// Creating BitmapSource
var bytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel) / 8;
var stride = bytesPerPixel * cf.FrameDescription.Width;
bmpSource = BitmapSource.Create(fd.Width, fd.Height, 96.0, 96.0, PixelFormats.Bgr32, null, colorData, stride);
// WritableBitmap to show on UI
wbmp = new WriteableBitmap(bmpSource);
FacePhoto.Source = wbmp;
}
}
private void SaveImage(BitmapSource image)
{
try
{
FileStream stream = new System.IO.FileStream(#"Frames\frame.jpg", System.IO.FileMode.OpenOrCreate);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.FlipHorizontal = true;
encoder.FlipVertical = false;
encoder.QualityLevel = 30;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
stream.Close();
}
catch (Exception)
{
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Tick += Timer_Tick;
timer.Start();
timer2 = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer2.Tick += Timer2_Tick;
timer2.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
SaveImage(bmpSource);
}
private async void Timer2_Tick(object sender, EventArgs e)
{
Title = "Detecting...";
FaceRectangle[] faceRects = await UploadAndDetectFaces(streamF);
Face[] faceAttributes = await UploadAndDetectFaceAttributes(streamF);
Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);
if (faceRects.Length > 0)
{
DrawingVisual visual = new DrawingVisual();
DrawingContext drawingContext = visual.RenderOpen();
drawingContext.DrawImage(bmpSource,
new Rect(0, 0, bmpSource.Width, bmpSource.Height));
double dpi = bmpSource.DpiX;
double resizeFactor = 96 / dpi;
foreach (var faceRect in faceRects)
{
drawingContext.DrawRectangle(
Brushes.Transparent,
new Pen(Brushes.Red, 2),
new Rect(
faceRect.Left * resizeFactor,
faceRect.Top * resizeFactor,
faceRect.Width * resizeFactor,
faceRect.Height * resizeFactor
)
);
}
drawingContext.Close();
RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
(int)(bmpSource.PixelWidth * resizeFactor),
(int)(bmpSource.PixelHeight * resizeFactor),
96,
96,
PixelFormats.Pbgra32);
faceWithRectBitmap.Render(visual);
FacePhoto.Source = faceWithRectBitmap;
}
if (faceAttributes.Length > 0)
{
foreach (var faceAttr in faceAttributes)
{
Label lb = new Label();
//Canvas.SetLeft(lb, lb.Width);
lb.Content = faceAttr.FaceAttributes.Gender;// + " " + faceAttr.Gender + " " + faceAttr.FacialHair + " " + faceAttr.Glasses + " " + faceAttr.HeadPose + " " + faceAttr.Smile;
lb.FontSize = 50;
lb.Width = 200;
lb.Height = 100;
stack.Children.Add(lb);
}
}
}
private async Task<FaceRectangle[]> UploadAndDetectFaces(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.OpenRead(imageFilePath))
{
var faces = await faceServiceClient.DetectAsync(imageFilePath);
var faceRects = faces.Select(face => face.FaceRectangle);
var faceAttrib = faces.Select(face => face.FaceAttributes);
return faceRects.ToArray();
}
}
catch (Exception)
{
return new FaceRectangle[0];
}
}
private async Task<Face[]> UploadAndDetectFaceAttributes(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.Open(imageFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var faces = await faceServiceClient.DetectAsync(imageFileStream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.HeadPose, FaceAttributeType.FacialHair });
return faces.ToArray();
}
}
catch (Exception)
{
return new Face[0];
}
}
}
Above code worked well. But, I want to convert each frame of Kinect Color Feed directly to Stream and I have no idea how to do it though I searched but nothing worked for me. If Somebody can help me then it'll be great. Thanks!
Instead of persisting the frame to a file in SaveImage, you can persist it to a MemoryStream, rewind it (by calling Position = 0), and send that stream to DetectAsync().
Also note that in UploadAndDetectFaces, you should send imageFileStream, not imageFilePath, to DetectAsync(). You probably don't want to call both UploadAndDetectFaces and UploadAndDetectFaceAttributes anyway, since you're just doubling your work (and quota/rate-limit hit.)

Wikipedia Image list show from wikipedia xml api

I am trying to write a code in which I got as xml format for the first image api from wikipedia. Now I want to parse it through c#. But I cannot get the image while running code. here is my code.
namespace WikiAPIWinForm
{
public partial class WikiForm : Form
{
private const string url1_Image1 = "https://en.wikipedia.org/w/api.php?action=query&titles=File:Schloss%20Neuschwanstein%202013.jpg&prop=imageinfo&iiprop=comment|url|dimensions&format=xml&iiurlwidth=300"; //show 1st image
private const string url1_Image2 = "https://en.wikipedia.org/w/api.php?action=query&titles=File:Neuschwanstein%20castle.jpg&prop=imageinfo&iiprop=comment|url|dimensions&format=xml&iiurlwidth=300";// show another image
private const string url1_Image3 = "https://en.wikipedia.org/w/api.php?action=query&titles=File:Hohenschwangau_-_Schloss_Neuschwanstein5.jpg&prop=imageinfo&iiprop=comment|url|dimensions&format=xml&iiurlwidth=300";// show another image
public WikiForm()
{
InitializeComponent();
}
XDocument xmlDocument1 = XDocument.Load(url1_Image1);
XDocument xmlDocument2 = XDocument.Load(url1_Image2);
XDocument xmlDocument3 = XDocument.Load(url1_Image3);
var image1 = (from page in xmlDocument1.Descendants("page")
select new AllImage
{
Title1 = page.Attribute("title").Value,
Imagerepository1 = page.Attribute("imagerepository").Value,
Url1 = page.Element("imageinfo").Element("ii").Attribute("thumburl").Value
});
ShowImages1(image1);
var image2 = (from page in xmlDocument2.Descendants("page")
select new AllImage
{
Title2 = page.Attribute("title").Value,
Imagerepository2 = page.Attribute("imagerepository").Value,
Url2 = page.Element("imageinfo").Element("ii").Attribute("thumburl").Value
});
ShowImages2(image2);
var image3 = (from page in xmlDocument3.Descendants("page")
select new AllImage
{
Title3 = page.Attribute("title").Value,
Imagerepository2 = page.Attribute("imagerepository").Value,
Url3 = page.Element("imageinfo").Element("ii").Attribute("thumburl").Value
});
ShowImages3(image3);
}
private void ShowImages1(IEnumerable<AllImage> image1)
{
var image = image1.First();
pictureLabel1.Text = image.Title1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.LoadAsync(image.Url1);// asynchronous loading
}
private void ShowImages2(IEnumerable<AllImage> image2)
{
var image = image2.First();
pictureLabel2.Text = image.Title2;
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.LoadAsync(image.Url2);// asynchronous loading
}
private void ShowImages3(IEnumerable<AllImage> image3)
{
var image = image3.First();
pictureLabel3.Text = image.Title3;
pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox3.LoadAsync(image.Url3);// asynchronous loading
}
}
You need something like
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false; // to prevent a new download until you have finished the old one
XDocument xmlDocument = XDocument.Load(url1_Image);
var images = (from page in xmlDocument.Descendants("page")
select new AllImage
{
Title = page.Attribute("title").Value,
Imagerepository = page.Attribute("imagerepository").Value,
Url = page.Element("imageinfo").Element("ii").Attribute("url").Value
});
ShowImages(images);
};
private void ShowImages(IEnumerable<AllImage> images)
{
var image = images.First();
label1.Text = image.Title;
pictureBox1.LoadAsync(image.Url); // asynchronous loading
}
After downloading the image you need to make the button available.
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
button1.Enabled = true;
}
We strongly recommend to give normal names to the controls. For example, buttonLoad, labelTitle, pictureBoxWikiImage.
In addition, I see in XML information about only one image. So, for what the IEnumerable collection?

Setting image in the view after downloading from web with JSON.Net

Let's say I have 3 image views in my xaml . I am downloading images from a server & now I want to set those images in my image views . How can I do that ? Please Help !
My Code :
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (int i = 0; i < container.MyBookList.Count; i++)
{
newData[i] = new data();
newData[i].id = container.MyBookList[i].ID;
newData[i].title = container.MyBookList[i].TITLE;
newData[i].type = container.MyBookList[i].TYPE;
newData[i].price = container.MyBookList[i].PRICE;
newData[i].downloadLink = container.MyBookList[i].DOWNLOADLINK;
string file_name = newData[i].downloadLink.ToString();
string image_uri = "http://www.banglanews24.com/images/imgAll/" + file_name;
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(image_uri), wc);
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{ //I can set just one image here....what should I do ?
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
image1.Source = image;
}
catch (Exception ex)
{
//Exception handle appropriately for your app
}
}
else
{
//Either cancelled or error handle appropriately for your app
}
}
This should do it:
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (int i = 0; i < container.MyBookList.Count; i++)
{
newData[i] = new data();
newData[i].id = container.MyBookList[i].ID;
newData[i].title = container.MyBookList[i].TITLE;
newData[i].type = container.MyBookList[i].TYPE;
newData[i].price = container.MyBookList[i].PRICE;
newData[i].downloadLink = container.MyBookList[i].DOWNLOADLINK;
string file_name = newData[i].downloadLink.ToString();
string image_uri = "http://www.banglanews24.com/images/imgAll/" + file_name;
Uri uri = new Uri(image_uri, UriKind.Relative);
ImageSource imgSource = new BitmapImage(uri);
if (i==0) image1.source = imgSource;
else if (i==1) image2.source = imgSource;
else if (i==2) image3.source = imgSource;
etc
}
You will find that your images will automatically be downloaded when you give it a Image URI.

Categories