Added react-teams-graph-upload-as-pdf sample

This commit is contained in:
mmsharepoint 2021-11-08 14:32:17 +01:00
parent ed653b53f3
commit b229a7dbe8
29 changed files with 26236 additions and 0 deletions

View File

@ -0,0 +1,33 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,12 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.13.0",
"libraryName": "react-teams-graph-upload-as-pdf",
"libraryId": "f10938fa-9fe7-4cb2-bc00-15902a2cfc66",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,67 @@
# react-teams-graph-upload-as-pdf
## Summary
This SPFx webpart (or TeamsTab) enables a user to upload a supported () file type via drag and drop while the uploaded file will be converted as PDF.
In SharePoint context it uploads to the default drive (library) while in Teams context it uses the current channel as a Folder name in the default drive.
It uses the following capabilities (mostly) on behalf of Microsoft Graph:
* Use HTML5 drag and drop event handling
* Writing normal files smaller 4MB
* Retrieving files with format=pdf conversion
## react-teams-graph-upload-as-pdf in action
![File upload via drag and drop, progress and result](./assets/UploadAnimated.gif)
A detailed functionality and technical description can be found in the [author's blog post](https://mmsharepoint.wordpress.com/2020/11/10/a-simple-spfx-file-upload-by-dragdrop-including-pdf-conversion/)
## Used SharePoint Framework Version
![version](https://img.shields.io/badge/version-1.13-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
react-teams-graph-upload-as-pdf| Markus Moeller ([@moeller2_0](http://www.twitter.com/moeller2_0))
## Version history
Version|Date|Comments
-------|----|--------
1.0|November 10, 2020|Initial release
1.1|November 08, 2021|Updated to SPFx 1.13 & Shared with PnP repo
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
---
## Minimal Path to Awesome
- Clone this repository
- Ensure that you are at the solution folder
- in the command-line run:
- **npm install**
- **gulp bundle --ship**
- **gulp package-solution --ship**
- Upload your package from /sharepoint/solution/... to your app catalog
- In SharePoint CA approve following web api permissions
- Files.ReadWrite
- Sites.ReadWrite.All
## Features
This webpart illustrates the following concepts:
- Use HTML5 drag and drop event handling
- [Writing normal files smaller 4MB](https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http)
- Retrieving files with [format=pdf](https://docs.microsoft.com/en-us/graph/api/driveitem-get-content-format?view=graph-rest-1.0&tabs=http) conversion
- [FluentUI Progress Indicator](https://developer.microsoft.com/en-us/fluentui#/controls/web/progressindicator)
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-teams-graph-upload-as-pdf" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"upload-file-as-pdf-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/uploadFileAsPdf/UploadFileAsPdfWebPart.js",
"manifest": "./src/webparts/uploadFileAsPdf/UploadFileAsPdfWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"UploadFileAsPdfWebPartStrings": "lib/webparts/uploadFileAsPdf/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-teams-graph-upload-as-pdf",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,31 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-teams-graph-upload-as-pdf-client-side-solution",
"id": "f10938fa-9fe7-4cb2-bc00-15902a2cfc66",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": ""
},
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "Files.ReadWrite"
},
{
"resource": "Microsoft Graph",
"scope": "Sites.ReadWrite.All"
}
]
},
"paths": {
"zippedPackage": "solution/react-teams-graph-upload-as-pdf.sppkg"
}
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,14 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,32 @@
{
"name": "react-teams-graph-upload-as-pdf",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.13.0",
"@microsoft/sp-lodash-subset": "1.13.0",
"@microsoft/sp-office-ui-fabric-core": "1.13.0",
"@microsoft/sp-property-pane": "1.13.0",
"@microsoft/sp-webpart-base": "1.13.0",
"office-ui-fabric-react": "7.174.1",
"react": "16.13.1",
"react-dom": "16.13.1"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.9": "0.4.47",
"@microsoft/sp-build-web": "1.13.0",
"@microsoft/sp-module-interfaces": "1.13.0",
"@microsoft/sp-tslint-rules": "1.13.0",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"gulp": "4.0.2"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,28 @@
export default class Utilities {
private static validExtensions: string[] = ["csv", "doc", "docx", "odp", "ods", "odt", "pot", "potm", "potx", "pps", "ppsx", "ppsxm", "ppt", "pptm", "pptx", "rtf", "xls", "xlsx"];
public static getFileExtension(fileName: string) {
if (fileName.indexOf('.') > 0) {
const extensions = fileName.split('.');
const fileExtension = extensions[extensions.length - 1];
return fileExtension;
}
}
public static getFileNameAsPDF(fileName: string) {
const orgExtension = this.getFileExtension(fileName);
const extensionStarts = fileName.lastIndexOf(orgExtension);
const namePart = fileName.substr(0, extensionStarts);
return namePart + `pdf`;
}
public static validFileExtension(fileName: string) {
const orgExtension = this.getFileExtension(fileName);
if (this.validExtensions.indexOf(orgExtension) > -1) {
return true;
}
else {
return false;
}
}
}

View File

@ -0,0 +1,71 @@
import { MSGraphClientFactory, MSGraphClient } from "@microsoft/sp-http";
export default class GraphService {
private client: MSGraphClient;
public async initialize (serviceScope): Promise<boolean> {
const graphFactory: MSGraphClientFactory = serviceScope.consume(MSGraphClientFactory.serviceKey);
return graphFactory.getClient()
.then((client) => {
this.client = client;
return true;
});
}
public async uploadTmpFileToOneDrive (file: File): Promise<string> {
const apiUrl = `me/drive/root:/TempUpload/${file.name}:/content`;
const response = await this.uploadFile(apiUrl, file);
const fileID = response.id;
return fileID;
}
public async downloadTmpFileAsPDF (fileID: string): Promise<Blob> {
const apiUrl = `me/drive/items/${fileID}/content?format=PDF`;
const response = await this.client
.api(apiUrl)
.responseType('blob')
.get();
return response;
}
// Alternative to responseType "blob"
// var reader = new FileReader();
// reader.onload = (e) => {
// var rawData = reader.result;
// const apiUrl4 = `me/drive/root:/TempUpload/Binary.pdf:/content`;
// this.client
// .api(apiUrl4)
// .put(rawData);
// }
// reader.readAsBinaryString(res2);
public async uploadFileToSiteAsPDF(siteID: string, file: Blob, fileName: string, channelName: string): Promise<string> {
const apiUrl = channelName !== '' ?
`sites/${siteID}/drive/root:/${channelName}/${fileName}:/content`:
`sites/${siteID}/drive/root:/${fileName}:/content`;
const response = await this.uploadFile(apiUrl, file);
return response.webUrl;
}
private async uploadFile(apiUrl: string, file: Blob) {
if (file.size <(4 * 1024 * 1024)) {
const resp = await this.client
.api(apiUrl)
.put(file);
return resp;
}
else {
// File.size>4MB, refer to https://mmsharepoint.wordpress.com/2020/01/12/an-outlook-add-in-with-sharepoint-framework-spfx-storing-mail-with-microsoftgraph/
return null;
}
}
public async deleteTmpFileFromOneDrive(fileID: string) {
const apiUrl = `me/drive/items/${fileID}`;
this.client
.api(apiUrl)
.delete();
}
}

View File

@ -0,0 +1,27 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "593257dd-3b84-4989-ae84-ef12ecd04e7d",
"alias": "UploadFileAsPdfWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart","TeamsTab"],
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Upload File as PDF" },
"description": { "default": "Allows to upload a (supported) file to be uploaded, but as PDF format instead of original" },
"officeFabricIconFontName": "PDF",
"properties": {
"description": "Upload File as PDF"
}
}]
}

View File

@ -0,0 +1,74 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { initializeIcons } from '@uifabric/icons';
import * as strings from 'UploadFileAsPdfWebPartStrings';
import UploadFileAsPdf from './components/UploadFileAsPdf';
import { IUploadFileAsPdfProps } from './components/IUploadFileAsPdfProps';
export interface IUploadFileAsPdfWebPartProps {
description: string;
}
export default class UploadFileAsPdfWebPart extends BaseClientSideWebPart<IUploadFileAsPdfWebPartProps> {
private teamsChannelName: string = '';
public onInit(): Promise<void> {
initializeIcons();
if (this.context.sdks.microsoftTeams) {
this.teamsChannelName = this.context.sdks.microsoftTeams.context.channelName;
}
return Promise.resolve();
}
public render(): void {
const url: URL = new URL(this.context.pageContext.site.absoluteUrl);
const siteID = `${url.hostname},${this.context.pageContext.site.id},${this.context.pageContext.web.id}`;
const element: React.ReactElement<IUploadFileAsPdfProps> = React.createElement(
UploadFileAsPdf,
{
serviceScope: this.context.serviceScope,
siteID: siteID,
channelName: this.teamsChannelName
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,3 @@
export interface IProgressComponentProps {
header: string;
}

View File

@ -0,0 +1,7 @@
import { ServiceScope } from "@microsoft/sp-core-library";
export interface IUploadFileAsPdfProps {
serviceScope: ServiceScope;
siteID: string;
channelName: string;
}

View File

@ -0,0 +1,19 @@
import * as React from 'react';
import { ProgressIndicator } from 'office-ui-fabric-react/lib/ProgressIndicator';
import { IProgressComponentProps } from './IProgressComponentProps';
export const ProgressComponent: React.FunctionComponent<IProgressComponentProps> = (props) => {
const [percentComplete, setPercentComplete] = React.useState(0);
const intervalDelay = 1;
const intervalIncrement = 0.01;
React.useEffect(() => {
if (percentComplete < 0.99) {
setTimeout(() => {setPercentComplete((intervalIncrement + percentComplete) % 1);}, intervalDelay);
}
});
return (
<ProgressIndicator label={props.header} percentComplete={percentComplete} />
);
};

View File

@ -0,0 +1,31 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.uploadFileAsPdf {
.fileCanvas {
position: absolute;
top: 10;
border: 1px solid black;
padding: 20px;
width: 100%;
height: 100%;
z-index: 10;
}
.background {
position: relative;
width: 400px;
height: 200px;
.inner {
position: absolute;
top: 45%;
left: 45%;
color: #ccc;
text-align: center;
.icon {
font-size: 80px;
}
}
}
.highlight {
background-color: rgba(211, 211, 211, 0.5);
}
}

View File

@ -0,0 +1,89 @@
import * as React from 'react';
import styles from './UploadFileAsPdf.module.scss';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import { IUploadFileAsPdfProps } from './IUploadFileAsPdfProps';
import GraphService from '../../../services/graphService';
import Utilities from '../../../services/Utilities';
import { ProgressComponent } from './ProgressComponent';
const UploadFileAsPdf: React.FunctionComponent<IUploadFileAsPdfProps> = (props) => {
const [highlight, setHighlight] = React.useState(false);
const [tmpFileUploaded, setTmpFileUploaded] = React.useState(false);
const [pdfFileDownloaded, setPDFFileDownloaded] = React.useState(false);
const [pdfFileUploadedDeleted, setPDFFileUploadedDeleted] = React.useState(false);
const [pdfFileUploadUrl, setPDFFileUploadUrl] = React.useState('');
const allowDrop = (event) => {
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = 'copy';
setTmpFileUploaded(false);
setPDFFileDownloaded(false);
setPDFFileUploadedDeleted(false);
};
const enableHighlight = (event) => {
allowDrop(event);
setHighlight(true);
};
const disableHighlight = (event) => {
allowDrop(event);
setHighlight(false);
};
const dropFile = (event) => {
allowDrop(event);
setHighlight(false);
let dt = event.dataTransfer;
let files = Array.prototype.slice.call(dt.files); //[...dt.files];
files.forEach(fileToUpload => {
if (Utilities.validFileExtension(fileToUpload.name)) {
uploadFile(fileToUpload);
}
});
};
const uploadFile = async (file:File) => {
const graphService: GraphService = new GraphService();
const initialized = await graphService.initialize(props.serviceScope);
if (initialized) {
const tmpFileID = await graphService.uploadTmpFileToOneDrive(file);
setTmpFileUploaded(true);
setTimeout(async () => {
const pdfBlob = await graphService.downloadTmpFileAsPDF(tmpFileID);
setPDFFileDownloaded(true);
const newFilename = Utilities.getFileNameAsPDF(file.name);
const fileUrl = await graphService.uploadFileToSiteAsPDF(props.siteID, pdfBlob, newFilename, props.channelName);
setPDFFileUploadUrl(fileUrl);
graphService.deleteTmpFileFromOneDrive(tmpFileID)
.then(() => {
setTimeout(() => {
setPDFFileUploadedDeleted(true);
}, 1000);
});
}, 800);
}
};
return (
<div className={ styles.uploadFileAsPdf }>
Drag your file here:
<div className={styles.background}>
<div className={`${styles.fileCanvas} ${highlight?styles.highlight:''}`}
onDragEnter={enableHighlight}
onDragLeave={disableHighlight}
onDragOver={allowDrop}
onDrop={dropFile}>
{tmpFileUploaded && <ProgressComponent header="File uploaded temp. to OneDrive" />}
{pdfFileDownloaded && <ProgressComponent header="File retrieved as PDF" />}
{pdfFileUploadUrl !== '' &&
<div>
<ProgressComponent header="File uploaded to target (and temp. file deleted)" />
{pdfFileUploadedDeleted && <div>File uploaded to target and available <a href={pdfFileUploadUrl}>here.</a></div>}
</div>}
</div>
{!tmpFileUploaded && <div className={styles.inner}><Icon className={styles.icon} iconName="PDF" /><br/>To generate a PDF</div>}
</div>
</div>
);
};
export default UploadFileAsPdf;

View File

@ -0,0 +1,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field"
}
});

View File

@ -0,0 +1,10 @@
declare interface IUploadFileAsPdfWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'UploadFileAsPdfWebPartStrings' {
const strings: IUploadFileAsPdfWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

View File

@ -0,0 +1,35 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.9/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"ES2015.Promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}

View File

@ -0,0 +1,29 @@
{
"extends": "./node_modules/@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": false,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}