Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More document preview changes #183

Merged
merged 3 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 8 additions & 11 deletions backend/src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,15 @@ export class AdminController {
@Get('preview-template/:id')
async previewTemplate(@Param('id') id: number, @Res() res) {
try {
// const pdfBuffer = await this.adminService.getPreviewPdf(id);
// const streamableFile = new stream.PassThrough();
// streamableFile.end(pdfBuffer);
// res.set({
// 'Content-Type': 'application/pdf',
// 'Content-Disposition': 'inline; filename=preview.pdf',
// 'Content-Security-Policy': "default-src 'self' https://*.gov.bc.ca data:; frame-src 'self' blob:;",
// });
// streamableFile.pipe(res);
const pdfBuffer = await this.adminService.getPreviewPdf(id);
const base64Data = pdfBuffer.toString('base64');
res.json({ data: base64Data });
const streamableFile = new stream.PassThrough();
streamableFile.end(pdfBuffer);
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline; filename=preview.pdf',
'Content-Security-Policy': "frame-src 'self' blob:;",
});
streamableFile.pipe(res);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
Expand Down
5 changes: 1 addition & 4 deletions frontend/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@
<link rel="stylesheet" href="/css/new.css" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta
http-equiv="Content-Security-Policy"
content="default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: content:; frame-src 'self' blob: data:"
/>
<meta http-equiv="Content-Security-Policy" content="frame-src 'self' blob:;" />
<link rel="apple-touch-icon" href="/images/bcid-apple-touch-icon.png" sizes="180x180" />
<link rel="icon" href="/images/bcid-favicon-32x32.png" sizes="32x32" type="image/png" />
<link rel="icon" href="/images/bcid-favicon-16x16.png" sizes="16x16" type="image/png" />
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/app/common/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ const fileDownloadPost = <T, M = {}>(parameters: ApiRequestParameters<M>): Promi
* @param url
* @param filename
*/
export const handleFilePreviewGet = async (url: string, filename: string): Promise<Blob | null> => {
export const handleFilePreviewGet = async (url: string): Promise<Blob | null> => {
try {
const getParameters = generateApiParameters(url);
return new Promise<Blob>((resolve, reject) => {
Expand Down
9 changes: 3 additions & 6 deletions frontend/src/app/common/manage-templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,11 @@ export const disableProvision = async (provisionId: number): Promise<void> => {
console.log(response);
};

export const previewTemplate = async (id: number, fileName: string): Promise<Blob | null> => {
export const previewTemplate = async (id: number): Promise<Blob | null> => {
const url = `${config.API_BASE_URL}/admin/preview-template/${id}`;
try {
const getParameters = api.generateApiParameters(url);
const response = await api.get<any>(getParameters);
const base64Data = response.data;
const blob = base64ToBlob(base64Data, 'application/pdf');
return blob;
const response = await api.handleFilePreviewGet(url);
return response;
} catch (error) {
console.error('Error retrieving preview:', error);
return null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,39 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import Button from 'react-bootstrap/Button';
import { previewTemplate } from '../../../common/manage-templates';

interface PreviewTemplateModalProps {
isOpen: boolean;
toggleModal: () => void;
pdfBlob: Blob | null;
templateId: number;
}

const PreviewTemplateModal: React.FC<PreviewTemplateModalProps> = ({ isOpen, toggleModal, pdfBlob }) => {
const iframeSrc = pdfBlob ? window.URL.createObjectURL(pdfBlob) : '';
const PreviewTemplateModal: React.FC<PreviewTemplateModalProps> = ({ isOpen, toggleModal, templateId }) => {
const [pdfUrl, setPdfUrl] = useState<string>('');

useEffect(() => {
if (isOpen && templateId) {
const getTemplate = async () => {
const blob = await previewTemplate(templateId);
if (blob) {
const url = window.URL.createObjectURL(blob);
setPdfUrl(url);
} else {
console.error('Failed to load the PDF document');
setPdfUrl('');
}
};

getTemplate();

return () => {
if (pdfUrl) {
window.URL.revokeObjectURL(pdfUrl);
setPdfUrl('');
}
};
}
}, [templateId, isOpen]);

const modalOverlayStyle: React.CSSProperties = {
position: 'fixed',
Expand Down Expand Up @@ -50,9 +75,9 @@ const PreviewTemplateModal: React.FC<PreviewTemplateModalProps> = ({ isOpen, tog
<div style={modalContentStyle} onClick={(e) => e.stopPropagation()}>
<div style={iframeContainerStyle}>
<h2>Preview Document</h2>
{iframeSrc && (
{pdfUrl && (
<iframe
src={iframeSrc}
src={pdfUrl}
title="Preview Document"
style={{ border: 'none', width: '100%', height: '100%' }}
allowFullScreen
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
} from '../../../common/manage-templates';
import { DocType, TemplateInfo } from '../../../types/types';
import { Button } from 'react-bootstrap';
import PreviewTemplateModal from '../../modal/admin/manage-templates/PreviewTemplateModal';
import PreviewTemplateModal from '../../modal/manage-templates/PreviewTemplateModal';
import EditTemplateModal from '../../modal/manage-templates/EditTemplateModal';

interface TemplateInfoTableProps {
Expand All @@ -23,7 +23,7 @@ const TemplateInfoTable: React.FC<TemplateInfoTableProps> = ({ documentType, ref
const [currentlyActive, setCurrentlyActive] = useState<number>();
const [loading, setLoading] = useState<boolean>(false);
const [isOpen, setIsOpen] = useState<boolean>(false);
const [pdfBlob, setPdfBlob] = useState<Blob | null>(null);
const [previewId, setPreviewId] = useState<number | null>(null);
const [isEditModalOpen, setisEditModalOpen] = useState<boolean>(false);
const [documentId, setDocumentId] = useState<number>(10);
const [documentName, setDocumentName] = useState<string>('');
Expand Down Expand Up @@ -73,15 +73,16 @@ const TemplateInfoTable: React.FC<TemplateInfoTableProps> = ({ documentType, ref
setIsOpen(!isOpen);
};

const handlePreviewTemplate = async (id: number, fileName: string) => {
const handlePreviewTemplate = async (id: number) => {
try {
setLoading(true);
const response = await previewTemplate(id, fileName);
if (response) {
setPdfBlob(response);
setIsOpen(true);
setLoading(false);
}
setPreviewId(id);
// const response = await previewTemplate(id, fileName);
// if (response) {
// setPdfBlob(response);
setIsOpen(true);
setLoading(false);
// }
} catch (error) {
console.log('Error downloading template');
console.log(error);
Expand Down Expand Up @@ -150,10 +151,7 @@ const TemplateInfoTable: React.FC<TemplateInfoTableProps> = ({ documentType, ref
columnHelper.accessor('preview', {
id: 'preview',
cell: (info) => (
<Button
variant="success"
onClick={() => handlePreviewTemplate(info.row.original.id, info.row.original.file_name)}
>
<Button variant="success" onClick={() => handlePreviewTemplate(info.row.original.id)}>
Preview
</Button>
),
Expand Down Expand Up @@ -224,7 +222,7 @@ const TemplateInfoTable: React.FC<TemplateInfoTableProps> = ({ documentType, ref
onUpload={onTemplateUpdated}
/>
)}
{isOpen && <PreviewTemplateModal isOpen={isOpen} toggleModal={toggleModal} pdfBlob={pdfBlob} />}
{isOpen && previewId && <PreviewTemplateModal isOpen={isOpen} toggleModal={toggleModal} templateId={previewId} />}
<DataTable
columns={columns}
data={templateData}
Expand Down
Loading