Get as Image generates wrong image - Google App Script

后端 未结 1 1559
故里飘歌
故里飘歌 2020-12-02 02:18

My goal is to create google documents using information from a google sheet with google app script.

I can generate a radar chart from the data in the google sheets.

相关标签:
1条回答
  • 2020-12-02 03:06

    How about this answer?

    Issue and workaround:

    I think that this might be a bug. In this case, as a workaround, I use a Google Slides which can directly put the chart created with Google Spreadsheet. When the blob is retrieved from the chart put to the Google Slides, the blob is the same with the chrat on Google Spreadsheet.

    Modified script:

    When your script is modified, please modify as follows.

    From:
    var image = sheet.getCharts()[0].getBlob().getAs('image/png');
    
    To:
    const slides = SlidesApp.create("temp");
    const imageBlob = slides.getSlides()[0].insertSheetsChartAsImage(chart).getAs("image/png");
    DriveApp.getFileById(slides.getId()).setTrashed(true);
    DriveApp.createFile(imageBlob);
    
    • When imageBlob is created with DriveApp.createFile(imageBlob) as a file, the following result can be obtained.

    Result:

    When image and imageBlob are created as a file, the left and right images are obtained, respectively.

    Note:

    • If you want to put the correct chart image to Google Document using this workaround, please modify as follows.

        const slides = SlidesApp.create("temp");
        const imageBlob = slides.getSlides()[0].insertSheetsChartAsImage(chart).getAs("image/png");
        DriveApp.getFileById(slides.getId()).setTrashed(true);
      
        // This script puts the retrieved image blob to the Google Document.
        DocumentApp.openById("### Document ID ###").getBody().insertImage(0, imageBlob);
      

    Reference:

    • insertSheetsChartAsImage(sourceChart)
    0 讨论(0)
提交回复
热议问题