Save a Canvas image as an image or pdf,

Source: Internet
Author: User

Save a Canvas image as an image or pdf,

Although a Canvas image can be converted to a binary stream string format through toDataURL (), the image cannot be sent if it is a little larger. Of course, if the requirement is simple, you can add an image element to the page, you can directly assign the converted stream to the src of the image to display the image.

However, most of the time, we also want to pop up a save box to save the image to the path we want, or add some statistics and analysis information to the pdf to save it as a pdf file, this requires processing in the background. You can create a new Web Browser in the background to load the current page, and then send the information of the obtained image stream to the foreground to display the Save dialog box, there is no limit on the length of characters that the background sends to the foreground. However, if it is saved as a pdf file, it will be placed in the pdf file. If the image is too long, it will be truncated; another method is to upload the parameters used to the backend. the backend uses GDI + to repeat Bitmap. Canvas can achieve this, And the backend GDI + can also achieve this, some implementations may be more convenient. The advantage of this method is that there is no image size limit.

I recently implemented a project using the second method. paste the code below:

1. Front-end code [Click the Save image button ]:

        var width = drawObject.getCanvas().width;var height = drawObject.getCanvas().height;var figures = drawObject.getCurrentFigures();$.ajax({url: "./WareHousePrintHandler.ashx?action=drawpng&width=" + width + "&height=" + height,type: "post",data: "datas=" + JSON.stringify(figures),success: function (fileName){$('#frameImage').attr('src', "./WareHousePrintHandler.ashx?action=getpng&fileName=" + fileName);},error: function (err){alert("Print failed.");}});

Upload the information to be drawn at the front end to a handler in the background through ajax. handler receives the parameters and saves the painted images to a shared path of IIS. The image name is returned to the front end, the front-end uses an iframe with a size of 0 to reload the page, use the image name to retrieve the image stream in the background, and the Save prompt box is displayed.

2. iframe code

<iframe width="0" height="0" id="frameImage" name="frameImage" frameborder="0" scrolling="no"></iframe>

3. Background code

if (action.ToString() == "drawpng"){if (context.Request["datas"] == null){return;}double w = double.Parse(context.Request["width"].ToString());double h = double.Parse(context.Request["height"].ToString());string allFigures = context.Server.UrlDecode(context.Request["datas"].ToString());List<DrawModel> figureList = AspSoft.WareHouse.Util.JsonHelper.JsonDeserialize<List<DrawModel>>(allFigures);WareHouseDrawing drawing = new WareHouseDrawing();string fileName = drawing.GetImageUrl((int)w, (int)h, figureList, filePath);context.Response.Write(fileName);//ms.WriteTo(Response.OutputStream);context.Response.End();}else if (action.ToString() == "getpng"){string fileName = context.Request["fileName"].ToString();string fullFileName = filePath + "/" + fileName;context.Response.AppendHeader("Content-Disposition", string.Format("Attachment; FileName={0}.png;", HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMdd_HHmmss"), System.Text.Encoding.UTF8)));context.Response.WriteFile(fullFileName);context.Response.End();}

GetImageUrl is a specific method of painting. Save the painted image to a shared path. It must be a shared path accessible by IIS, not a local path. The second request is to obtain png, actually, the png path is obtained. iframe automatically obtains the stream information of the image after loading the image path. This is automatically handled by the browser. The key here is to add Attachment, it must be sent as an attachment.

This method can only be completed after two requests are sent, because if the image is requested in the src mode of iframe for the first time, because the request can only be made in querystring mode, big data cannot be transmitted, because the amount of data to be drawn is large, ajax requests must be used first. The same is true for PDF. It is to put bitmap information in PDF.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.