Angular : 将 blob 转换为 pdf
Angular : converting blob into pdf
我创建了一个 SPRING BOOT 服务,它可以存储不同类型的文件。当我尝试将此服务用于 ANGULAR 时,图像也能正常工作,但是当我尝试使用 ng-pdf-viewer 显示 pdf 文件时,它对我不起作用。
my component.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.
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
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
<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
有什么帮助吗?..
您不能在 pdf 查看器中将 blob 文件作为 src 传递,您必须将其转换为 safeUrl 才能预览。希望这会有所帮助。
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(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;
}
我创建了一个 SPRING BOOT 服务,它可以存储不同类型的文件。当我尝试将此服务用于 ANGULAR 时,图像也能正常工作,但是当我尝试使用 ng-pdf-viewer 显示 pdf 文件时,它对我不起作用。
my component.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.
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
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
<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
有什么帮助吗?..
您不能在 pdf 查看器中将 blob 文件作为 src 传递,您必须将其转换为 safeUrl 才能预览。希望这会有所帮助。
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(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;
}