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

Export Notes as PDF #504

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
607 changes: 484 additions & 123 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
},
"dependencies": {
"@reduxjs/toolkit": "^1.4.0",
"@types/marked": "^2.0.2",
"axios": "^0.21.1",
"clipboard-polyfill": "^3.0.1",
"codemirror": "^5.58.1",
Expand All @@ -67,11 +68,13 @@
"express": "^4.17.1",
"helmet": "^4.1.1",
"jszip": "^3.5.0",
"marked": "^2.0.3",
"mousetrap": "^1.6.5",
"mousetrap-global-bind": "^1.1.0",
"path-browserify": "^1.0.1",
"prettier": "^2.1.2",
"process": "^0.11.10",
"puppeteer": "^9.0.0",
"react": "^16.14.0",
"react-beautiful-dnd": "^13.0.0",
"react-codemirror2": "^7.2.1",
Expand Down Expand Up @@ -101,6 +104,7 @@
"@types/cors": "^2.8.8",
"@types/express": "^4.17.8",
"@types/faker": "^5.1.2",
"@types/file-saver": "^2.0.2",
"@types/helmet": "0.0.48",
"@types/jest": "^26.0.14",
"@types/jszip": "^3.4.1",
Expand Down
8 changes: 7 additions & 1 deletion src/client/containers/NoteMenuBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
Settings,
Sun,
Moon,
FileText,
Clipboard as ClipboardCmp,
} from 'react-feather'

Expand All @@ -23,7 +24,7 @@ import {
toggleDarkTheme,
updateCodeMirrorOption,
} from '@/slices/settings'
import { toggleFavoriteNotes, toggleTrashNotes } from '@/slices/note'
import { toggleFavoriteNotes, toggleTrashNotes, downloadPDFNotes } from '@/slices/note'
import { getCategories, getNotes, getSync, getSettings } from '@/selectors'
import { downloadNotes, isDraftNote, getShortUuid, copyToClipboard } from '@/utils/helpers'
import { sync } from '@/slices/sync'
Expand Down Expand Up @@ -89,6 +90,8 @@ export const NoteMenuBar = () => {
// ===========================================================================

const downloadNotesHandler = () => downloadNotes([activeNote], categories)
const downloadNotesPDFHandler = () =>
dispatch(downloadPDFNotes({ notes: [activeNote], categories }))
const favoriteNoteHandler = () => _toggleFavoriteNotes(activeNoteId)
const trashNoteHandler = () => _toggleTrashNotes(activeNoteId)
const syncNotesHandler = () => _sync(notes, categories)
Expand Down Expand Up @@ -126,6 +129,9 @@ export const NoteMenuBar = () => {
<button className="note-menu-bar-button">
<Download size={18} onClick={downloadNotesHandler} />
</button>
<button className="note-menu-bar-button">
<FileText size={18} onClick={downloadNotesPDFHandler} />
</button>
<button
className="note-menu-bar-button uuid"
onClick={() => {
Expand Down
11 changes: 9 additions & 2 deletions src/client/containers/SettingsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
toggleDarkTheme,
updateNotesSortStrategy,
} from '@/slices/settings'
import { updateNotes, importNotes } from '@/slices/note'
import { updateNotes, importNotes, downloadPDFNotes } from '@/slices/note'
import { logout } from '@/slices/auth'
import { importCategories } from '@/slices/category'
import { shortcutMap, notesSortOptions, directionTextOptions } from '@/utils/constants'
Expand Down Expand Up @@ -113,6 +113,7 @@ export const SettingsModal: React.FC = () => {
_updateCodeMirrorOption('direction', selectedOption.value)
}
const downloadNotesHandler = () => downloadNotes(notes, categories)
const downloadNotesPDFHandler = () => dispatch(downloadPDFNotes({ notes, categories }))
const backupHandler = () => backupNotes(notes, categories)
const importBackupHandler = async (json: File) => {
const content = await json.text()
Expand Down Expand Up @@ -233,13 +234,19 @@ export const SettingsModal: React.FC = () => {
))}
</TabPanel>
<TabPanel label="Data management" icon={Archive}>
<p>Download all notes as Markdown files in a zip.</p>
<p>Download all notes as files in a zip.</p>
<IconButton
dataTestID={TestID.SETTINGS_MODAL_DOWNLOAD_NOTES}
handler={downloadNotesHandler}
icon={Download}
text={LabelText.DOWNLOAD_ALL_NOTES}
/>
<IconButton
dataTestID={TestID.SETTINGS_MODAL_DOWNLOAD_NOTES}
handler={downloadNotesPDFHandler}
icon={Download}
text={LabelText.DOWNLOAD_ALL_NOTES_PDF}
/>
<p>Export TakeNote data as JSON.</p>
<IconButton
handler={backupHandler}
Expand Down
81 changes: 79 additions & 2 deletions src/client/sagas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { all, put, takeLatest, select } from 'redux-saga/effects'
import dayjs from 'dayjs'
import axios from 'axios'

import { LabelText } from '@resources/LabelText'
import { requestCategories, requestNotes, requestSettings, saveState, saveSettings } from '@/api'
import { loadCategories, loadCategoriesError, loadCategoriesSuccess } from '@/slices/category'
import { loadNotes, loadNotesError, loadNotesSuccess } from '@/slices/note'
import { loadNotes, loadNotesError, loadNotesSuccess, downloadPDFNotes } from '@/slices/note'
import { sync, syncError, syncSuccess } from '@/slices/sync'
import { login, loginSuccess, loginError, logout, logoutSuccess } from '@/slices/auth'
import {
Expand All @@ -17,7 +18,7 @@ import {
toggleSettingsModal,
updateNotesSortStrategy,
} from '@/slices/settings'
import { SyncAction } from '@/types'
import { SyncAction, DownloadPDFAction, NoteItem, CategoryItem } from '@/types'
import { getSettings } from '@/selectors'

const isDemo = process.env.DEMO
Expand Down Expand Up @@ -118,12 +119,88 @@ function* syncSettings() {
} catch (error) {}
}

export const getNoteTitle = (text: string): string => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of duplicating this code, it can be imported.

// Remove whitespace from both ends
// Get the first n characters
// Remove # from the title in the case of using markdown headers in your title
const noteText = text.trim().match(/[^#]{1,45}/)

// Get the first line of text after any newlines
// In the future, this should break on a full word
return noteText ? noteText[0].trim().split(/\r?\n/)[0] : LabelText.NEW_NOTE
}

export const noteWithFrontmatter = (note: NoteItem, category?: CategoryItem): string =>
`---
title: ${getNoteTitle(note.text)}
created: ${note.created}
lastUpdated: ${note.lastUpdated}
category: ${category?.name ?? ''}
---

${note.text}`

function* downloadAsPDF({ payload }: DownloadPDFAction) {
try {
const { notes } = payload
const headers = {
'Content-Type': 'application/pdf',
}
if (notes.length === 1) {
yield axios({
method: 'POST',
url: '/api/note/download',
data: payload,
responseType: 'blob',
}).then((res) => {
const file = new Blob([res.data], { type: 'application/pdf' })
const link = document.createElement('a')
const fileURL = URL.createObjectURL(file)
link.href = fileURL
link.setAttribute('download', `${getNoteTitle(notes[0].text)}.pdf`)
document.body.appendChild(link)
if (document.createEvent) {
const event = document.createEvent('MouseEvents')
event.initEvent('click', true, true)
link.dispatchEvent(event)
} else {
link.click()
}
})
} else {
yield axios({
method: 'POST',
url: '/api/note/downloadAll',
data: payload,
responseType: 'blob',
}).then((res) => {
const file = new Blob([res.data], { type: 'application/zip' })
const link = document.createElement('a')
const fileURL = URL.createObjectURL(file)
link.href = fileURL
link.setAttribute('download', `notesPDF.zip`)
document.body.appendChild(link)
if (document.createEvent) {
const event = document.createEvent('MouseEvents')
event.initEvent('click', true, true)
link.dispatchEvent(event)
} else {
link.click()
}
})
}
} catch (error) {
yield put(loadCategoriesError(error.message))
}
}

// If any of these functions are dispatched, invoke the appropriate saga
function* rootSaga() {
yield all([
takeLatest(login.type, loginUser),
takeLatest(logout.type, logoutUser),
takeLatest(loadNotes.type, fetchNotes),
takeLatest(downloadPDFNotes.type, downloadAsPDF),
takeLatest(loadCategories.type, fetchCategories),
takeLatest(loadSettings.type, fetchSettings),
takeLatest(sync.type, syncData),
Expand Down
9 changes: 8 additions & 1 deletion src/client/slices/note.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { v4 as uuid } from 'uuid'

import { Folder, NotesSortKey } from '@/utils/enums'
import { NoteItem, NoteState } from '@/types'
import { NoteItem, NoteState, CategoryItem } from '@/types'
import { isDraftNote } from '@/utils/helpers'
import { getNotesSorter } from '@/utils/notesSortStrategies'

Expand Down Expand Up @@ -313,6 +313,12 @@ const noteSlice = createSlice({
]
state.loading = false
},
downloadPDFNotes: (
state,
{ payload }: PayloadAction<{ notes: NoteItem[]; categories: CategoryItem[] }>
) => {
state.loading = false
},
},
})

Expand All @@ -338,6 +344,7 @@ export const {
loadNotesError,
loadNotesSuccess,
importNotes,
downloadPDFNotes,
} = noteSlice.actions

export default noteSlice.reducer
5 changes: 5 additions & 0 deletions src/client/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ export interface SyncAction {
payload: SyncPayload
}

export interface DownloadPDFAction {
type: typeof sync.type
payload: SyncPayload
}

//==============================================================================
// Events
//==============================================================================
Expand Down
3 changes: 2 additions & 1 deletion src/resources/LabelText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export enum LabelText {
WELCOME_TO_TAKENOTE = 'Welcome to Takenote!',
RENAME = 'Rename category',
ADD_CONTENT_NOTE = 'Please add content to this new note to access the menu options.',
DOWNLOAD_ALL_NOTES = 'Download all notes',
DOWNLOAD_ALL_NOTES = 'Download all notes as Markdown',
DOWNLOAD_ALL_NOTES_PDF = 'Download all notes as PDF',
BACKUP_ALL_NOTES = 'Export backup',
IMPORT_BACKUP = 'Import backup',
TOGGLE_FAVORITE = 'Toggle favorite',
Expand Down
70 changes: 70 additions & 0 deletions src/server/handlers/note.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { Request, Response } from 'express'
import puppeteer from 'puppeteer'
import marked from 'marked'
import JSZip from 'jszip'

import { NoteItem, CategoryItem } from '@/types'

export const getNoteTitle = (text: string): string => {
// Remove whitespace from both ends
// Get the first n characters
// Remove # from the title in the case of using markdown headers in your title
const noteText = text.trim().match(/[^#]{1,45}/)

// Get the first line of text after any newlines
// In the future, this should break on a full word
return noteText ? noteText[0].trim().split(/\r?\n/)[0] : 'New note'
}

export const noteWithFrontmatter = (note: NoteItem, category?: CategoryItem): string =>
`---
title: ${getNoteTitle(note.text)}
created: ${note.created}
lastUpdated: ${note.lastUpdated}
category: ${category?.name ?? ''}
---

${note.text}`

export default {
download: async (request: Request, response: Response) => {
const {
body: { notes },
} = request
const element = marked(notes[0].text)
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] })
const page = await browser.newPage()
await page.setContent(element)
await page.pdf({ format: 'a4' }).then((pdf) => {
response.setHeader('Content-Disposition', `attachment; filename=123.pdf`)
response.send(pdf)
})
},
downloadAll: async (request: Request, response: Response) => {
const {
body: { notes },
} = request
const pdfFiles: any = []
const fileNames: string[] = []
const zip = new JSZip()
await Promise.all(
notes.map(async (note: any) => {
const element = marked(note.text)
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] })
const page = await browser.newPage()
await page.setContent(element)
const pdf = await page.pdf({ format: 'a4' })
pdfFiles.push(pdf)
fileNames.push(`${getNoteTitle(note.text)} (${note.id.substring(0, 6)}).pdf`)

return pdf
})
)

pdfFiles.map((files: any, index: number) => zip.file(fileNames[index], files))
zip.generateAsync({ type: 'nodebuffer' }).then((content) => {
response.setHeader('Content-Disposition', `attachment; filename=notes.zip`)
response.send(content)
})
},
}
2 changes: 2 additions & 0 deletions src/server/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import express from 'express'

import authRoutes from './auth'
import syncRoutes from './sync'
import noteRoutes from './note'

const router = express.Router()

router.use('/auth', authRoutes)
router.use('/sync', syncRoutes)
router.use('/note', noteRoutes)

export default router
15 changes: 15 additions & 0 deletions src/server/router/note.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import express from 'express'

import noteHandler from '../handlers/note'
import checkAuth from '../middleware/checkAuth'
import getUser from '../middleware/getUser'

const router = express.Router()

router.post('/download', noteHandler.download)
router.post('/downloadAll', noteHandler.downloadAll)
router.post('/health', (req, res) => {
res.send(200)
})

export default router