简体   繁体   English

角度:将 blob 转换为 pdf

[英]Angular : converting blob into pdf

i created a SPRING BOOT service which can store different type of files.我创建了一个 SPRING BOOT 服务,它可以存储不同类型的文件。 when i tried to consume this service into ANGULAR , the images works as well but when i try to display the pdf files with ng-pdf-viewer it doesn't work for me.当我尝试将此服务用于 ANGULAR 时,图像也可以正常工作,但是当我尝试使用 ng-pdf-viewer 显示 pdf 文件时,它对我不起作用。

my component.ts:我的组件.ts:

export class AppComponent {
  constructor(private httpClient: HttpClient) {}
  tag: string;
  selectedFile: File;
  retrievedFile: any;
  base64Data: any;
  retrieveResonse: any;
  message: string;
  UserTag: any;
 //Gets called when the user selects a file
  public onFileChanged(event) {
    //Select File
    this.selectedFile = event.target.files[0];
  }

//Gets called when the user clicks on submit to upload the file //当用户点击提交上传文件时调用

  onUpload() {
    console.log(this.selectedFile);

//FormData API provides methods and properties to allow us easily prepare form data to be sent with POST HTTP requests. //FormData API 提供了一些方法和属性,让我们可以轻松地准备表单数据以通过 POST HTTP 请求发送。

    const uploadImageData = new FormData();
    uploadImageData.append("file", this.selectedFile, this.selectedFile.name);
    uploadImageData.append("tag", this.tag);

    //Make a call to the Spring Boot Application to save the file
    this.httpClient
      .post("http://localhost:8080/do", uploadImageData, {
        observe: "response"
      })
      .subscribe(response => {
        if (response.status === 200) {
          this.message = "Image uploaded successfully";
        } else {
          this.message = "Image not uploaded successfully";
        }
      });
  }

//Gets called when the user clicks on retrieve filebutton to get the image from back end //当用户点击检索文件按钮从后端获取图像时调用

  getFile() {
    //Make a call to Spring Boot to get the file Bytes.
    this.httpClient
      .get("http://localhost:8080/get/" + this.UserTag)
      .subscribe(res => {
        this.retrieveResonse = res;
        this.base64Data = this.retrieveResonse.fileContent;
        if (
          this.retrieveResonse.fileType == "jpg" ||
          this.retrieveResonse.fileType == "png" ||
          this.retrieveResonse.fileType == "jpeg"
        ) {
          this.retrievedFile = "data:image/jpg;base64," + this.base64Data;
        }

        if (this.retrieveResonse.fileType == "pdf") {
          var blob = new Blob([this.base64Data], { type: "application/pdf" });
          this.retrievedFile = blob;
        }
      });
  }
}

the get method:获取方法:

public DBFile getFile( String fileTag) throws IOException {

        final Optional<DBFile> retrievedFile = fileRepo.findByFileTag(fileTag);
        DBFile img = new DBFile(retrievedFile.get().getName(), retrievedFile.get().getFileType(),
                decompressBytes(retrievedFile.get().getFileContent()),retrievedFile.get().getAddedAt(),retrievedFile.get().getFileTag());

the decompress method: // uncompress the file bytes before returning it to the angular application解压缩方法:// 在将文件字节返回给 angular 应用程序之前对其进行解压缩

    public static byte[] decompressBytes(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }
            outputStream.close();
        } catch (IOException ioe) {
        } catch (DataFormatException e) {
        }
        return outputStream.toByteArray();
    }

    return img;
}

my component.HTML我的组件.HTML

 <div class="container row"> <div class="col-md-12"> <h1>Upload Image</h1> </div> </div> <div class="container row"> <div class="col-md-6"> <input type="file" (change)="onFileChanged($event)" /> </div> <div class="col-md-6"> <div class="form-group"> <label for="form">tag</label> <input type="text" class="form-control" id="tag" [(ngModel)]="tag" required /> </div> </div> <div class="col-md-6"> <input type="button" (click)="onUpload()" value="upload" /> </div> </div> <hr /> <div class="container row"> <div class="col-md-12"> <div *ngIf="message">{{ message }}</div> </div> </div> {{ this.retrieveResonse | json }} <div class="container row"> <div class="col-md-6"> <input type="text" class="form-control" id="name" placeholder="File Tag" [(ngModel)]="UserTag" name="name" /> </div> <div class="col-md-6"> <input type="button" (click)="getFile()" value="Get File" /> </div> </div> <div class="container row"> <div class="col-md-12"> <div> <pdf-viewer [src]="retrievedFile" [render-text]="true" style="display: block;" ></pdf-viewer> </div> </div> </div>

console error: photo of the console error控制台错误:控制台错误的照片

any help guys please?..请问各位有什么帮助吗?...

You cant pass the blob file as src in pdf viewer, you have to convert it to safeUrl to preview.您不能在 pdf 查看器中将 blob 文件作为 src 传递,您必须将其转换为 safeUrl 才能预览。 Hope this will help.希望这会有所帮助。

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; // import
constructor(private sanitizer: DomSanitizer) // include in constructor

 if (this.retrieveResonse.fileType == "pdf") {
          var blob = new Blob([this._base64ToArrayBuffer(this.base64Data)], {
        type: "application/doc"
      });


      const url = URL.createObjectURL(blob);

      this.retrievedFile = window.open(url);

the base64ToArrayBuffer methods: base64ToArrayBuffer 方法:

_base64ToArrayBuffer(base64) {
    const binary_string = window.atob(this.base64Data);
    const len = binary_string.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM