|
17 | 17 | # You should have received a copy of the GNU Lesser General Public License |
18 | 18 | # along with python-transip. If not, see <https://www.gnu.org/licenses/>. |
19 | 19 |
|
| 20 | +import os |
| 21 | +import base64 |
| 22 | + |
20 | 23 | from typing import Optional, Type |
21 | 24 |
|
22 | 25 | from transip.base import ApiService, ApiObject |
|
25 | 28 | ObjectDeleteMixin, ObjectUpdateMixin, |
26 | 29 | CreateAttrsTuple, UpdateAttrsTuple |
27 | 30 | ) |
| 31 | +from transip.exceptions import TransIPIOError |
28 | 32 |
|
29 | 33 |
|
30 | 34 | class ApiTestService(ApiService): |
@@ -197,6 +201,44 @@ def items(self) -> InvoiceItemService: |
197 | 201 | parent=self # type: ignore |
198 | 202 | ) |
199 | 203 |
|
| 204 | + def pdf(self, file_path: str) -> Optional[str]: |
| 205 | + """ |
| 206 | + Write a invoice to a PDF file. |
| 207 | +
|
| 208 | + Args: |
| 209 | + file_path (str): Path to PDF file, if the path is a directory to |
| 210 | + PDF is saved using its invoice number. |
| 211 | +
|
| 212 | + Returns: |
| 213 | + str: The absolute path to the saved PDF file. |
| 214 | +
|
| 215 | + Raises: |
| 216 | + TransIPIOError: If the PDF data couldn't be written to file. |
| 217 | + """ |
| 218 | + invoice_id = self.get_id() |
| 219 | + if not invoice_id: |
| 220 | + return None |
| 221 | + |
| 222 | + # Retrieve the base64 encoded PDF data |
| 223 | + encoded = self.service.client.get(f"/invoices/{invoice_id}/pdf")["pdf"] |
| 224 | + data = base64.b64decode(encoded.encode('ascii')) |
| 225 | + |
| 226 | + file_path = os.path.abspath(file_path) |
| 227 | + if os.path.isdir(file_path): |
| 228 | + file_path = os.path.join(file_path, f"{invoice_id}.pdf") |
| 229 | + if os.path.exists(file_path): |
| 230 | + raise TransIPIOError(f"File {file_path} already exists") |
| 231 | + |
| 232 | + try: |
| 233 | + with open(file_path, 'wb') as pdf_file: |
| 234 | + pdf_file.write(data) |
| 235 | + except OSError as exc: |
| 236 | + raise TransIPIOError( |
| 237 | + f"Unable to write PDF file {file_path}" |
| 238 | + ) from exc |
| 239 | + |
| 240 | + return file_path |
| 241 | + |
200 | 242 |
|
201 | 243 | class InvoiceService(GetMixin, ListMixin, ApiService): |
202 | 244 |
|
|
0 commit comments